据说使用太多Session
是不好的,因为它“污染了全局命名空间”。现在,我不太清楚这意味着什么(我可以很容易地想到更多要使用的名称...),但我已经开始使用 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 最简单的用例,但它甚至不能做到这一点?我错过了什么?
最佳答案
使用Template.onCreated
创建reactiveVars。
您必须在任何 Controller 代码运行之前实例化您的reactiveVar,以便Tracker 能够正确跟踪您的reactiveVar
。 onRendered
最适合用于操作 DOM 的函数,并且运行得太晚,无法可靠地确保 addingItem
在助手运行时存在,正如您遇到的那样。
这就是 onCreated
的最佳用途。这样,当您的帮助程序/ Controller 代码运行时,您的reactiveVar就可以确保存在。
Template.AddingItem.onCreated(function() {
this.addingItem = new ReactiveVar(false)
})
为了将来的引用,Sessions
实际上只是具有全局范围的 reactiveVars
...它们没有什么神奇之处。它是 reactiveVars
一直向下。
关于javascript - 如何保持reactiveVars模板的作用域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34519364/