编辑:现在在 Meteor 0.8.3 中更容易实现:
模板:
<template name="docTitle">
<span class="editable" title="Rename this document" data-autotext="never">{{this}}</span>
</template>
Code:
Template.docTitle.rendered = ->
tmplInst = this
this.autorun ->
# Trigger this whenever data source changes
Blaze.getCurrentData()
# Destroy old editable if it exists
tmplInst.$(".editable").editable("destroy").editable
display: ->
success: (response, newValue) -> # do stuff
为了最有效地实现这一点,请确保可编辑模板的数据上下文只是正在编辑的字段,如上面的示例所示{{> docTitle someHelper}}
.
以下为 Meteor 0.8.0 至 0.8.2 的过时信息
我也必须这样做,但不确定是否在我的应用程序中使用全局助手。所以我尝试通过改变可编辑的行为来实现它。
之后需要做的主要事情仔细阅读文档和来源是:
- 从字段文本设置表单的值
- 覆盖
display
函数使得由 Meteor 更新的文本的反应性不会中断
- 确保以上两个功能不会被破坏
这是代码(对 Coffeescript 表示歉意):
Template.foo.rendered = ->
container = @$('div.editable')
settings =
# When opening the popover, get the value from text
value: -> $.trim container.text()
# Don't set innerText ourselves, let Meteor update to preserve reactivity
display: ->
success: (response, newValue) =>
FooCollection.update @data._id,
$set: { field: newValue }
# Reconstruct the editable so it shows the correct form value next time
container.editable('destroy').editable(settings)
container.editable(settings)
这很丑陋,因为它会在设置新值后销毁并重新创建弹出窗口,以便表单字段从正确的值更新。
经过更多的逆向工程后,我找到了一种更干净的方法来执行此操作,并且不涉及破坏可编辑内容。加迪是对的container.data().editableContainer.formOptions.value
与此有关。这是因为这个值是更新后设置因为 x-editable 认为它现在可以缓存它。嗯,它不能,所以我们用原始函数替换它,以便继续从文本字段更新值。
Template.tsAdminBatchEditDesc.rendered = ->
container = @$('div.editable')
grabValue = -> $.trim container.text() # Always get reactively updated value
container.editable
value: grabValue
display: -> # Never set text; have Meteor update to preserve reactivity
success: (response, newValue) =>
Batches.update @data._id,
$set: { desc: newValue }
# Thinks it knows the value, but it actually doesn't - grab a fresh value each time
Meteor.defer -> container.data('editableContainer').formOptions.value = grabValue
Notes:
-
$.trim
以上摘自渲染值的默认行为
- 有关此的更多讨论,请参阅https://github.com/nate-strauser/meteor-x-editable-bootstrap/issues/15
- 这都是一个丑陋的黑客行为,希望将来我们能在 Meteor 中看到对双向变量绑定的更好支持。
将来我会尝试使其更加简洁,等待 Meteor 更好地支持响应式依赖数据。