如何保持reactiveVars模板作用域?

时间:2015-12-29 21:28:18

标签: javascript meteor

据说使用太多Sessions是不好的,因为它“污染了全局命名空间”。现在,我并不确切地知道这意味着什么(我可以很容易地想到要使用更多的名字......)但我已经开始使用ReactiveVar了,但它似乎很复杂且有问题,所以我想知道是什么好处是。

例如,这个简单的用例会引发错误:

Template.AddingItem.onRendered(function() {
    this.addingItem = new ReactiveVar(false)
})

Template.AddingItem.events({

    'click .add-new-item.button': function(event, template) {
        var addingItem = template.addingItem.get()
        if (addingItem === false) {
            template.addingItem.set(true)
        }
        else {
            template.addingItem.set(false)
        }
     }
})

Template.AddingItem.helpers({

    isAddingItem: function() {
        return Template.instance().addingItem.get()
    },
 })

模板:

{{#if isAddingItem}}
    <div>Showing something</div>
{{/if}}

有时帮助程序会在onRendered之前运行,并且无法返回任何内容,因此页面会出错。这实际上是ReactiveVar的最简单的用例,它甚至不能做到这一点吗?我错过了什么?

1 个答案:

答案 0 :(得分:1)

使用Template.onCreated创建reactiveVars

您必须在任何控制器代码运行之前实例化您的reactiveVar ,以便Tracker可以正确跟踪您的reactiveVaronRendered最适合用于操作DOM的函数,并且运行得太晚,以便在帮助程序运行时可靠地确保addingItem存在,就像您遇到的那样。

onCreated最适合的是什么。这样,当你的助手/控制器代码运行时,你的reactiveVar就会存在。

Template.AddingItem.onCreated(function() {
  this.addingItem = new ReactiveVar(false)
})

为了将来参考,Sessions实际上只是reactiveVars具有全球范围......对他们来说并不神奇。它reactiveVars一路向下。