【问题标题】:How to update data in Meteor using Reactivevar如何使用 Reactivevar 更新 Meteor 中的数据
【发布时间】:2014-12-22 16:26:11
【问题描述】:

我有一个带有表单的页面。在此表单中,用户可以使用键和值添加多行。有一个限制是 customFields 是动态创建的,而不是从任何订阅的集合中创建的。 ...html

<template name="main">
{{#each customFields}}
                    <div>
                        <input type="text" value="{{key}}"/>
                        <input type="text" style="width: 300px;" value="{{value}}"/>
                    </div>
                {{/each}}
</template

....路由器.js

Router.route 'products.add',
  path: '/products/add/:_id'
  data:
    customFields:[]

....products.js

#using customFieldSet as Reactive Var from meteor package
Template.product.created = ->
  @customFieldSet = new ReactiveVar([])


Template.product.rendered = ->
  self = this
  Tracker.autorun ->
    arr = self.customFieldSet.get()
    self.data.customFields = arr
Template.product.events(
'click .productForm__addField': (e)->
t = Template.instance()
    m = t.customFieldSet.get()
    console.log t
    m.push(
      key: ''
      value: ''
    )
    t.customFieldSet.set m

....

最后一个事件将在我单击按钮时触发。它在页面中添加另一行键和值为空的行。

请告诉我为什么我实际上看到反应变量 customFieldSet 更新了,但 html 中没有任何动态变化。

P/s:我猜 customFields 不是通过 Iron 路由器更新的。

【问题讨论】:

  • 这可能是因为分配给self.data.customFields不会触发模板重新渲染。

标签: javascript meteor


【解决方案1】:

基本上,你做对了。但是,您不应该将新的响应式数据分配给模板的数据上下文,而应该直接从您的助手访问它:

Template.product.helpers({
  customFileds: function () {
    return Template.instance().customFiledsSet.get();
  },
});

现在您可以在模板代码中使用{{customFields}},它应该可以响应式地工作。请记住,{{this.customFileds}}{{./customFileds}} 在这种情况下不起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-25
    • 2015-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多