Reputation: 2065
It is said that using too many Sessions
is bad because it "pollutes the global namespace". Now, I don't exactly know what that means (I can easily think of many more names to use...) but I have started to use ReactiveVar
instead, but it seems complicated and buggy, so I wonder what the benefits are.
For example, this simple use case throws an error:
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()
},
})
Template:
{{#if isAddingItem}}
<div>Showing something</div>
{{/if}}
Sometimes the helper runs before onRendered
and can't return anything, so the page bugs out. This is literally the easiest use case for ReactiveVar
and it can't even do that right? What am I missing?
Upvotes: 0
Views: 39
Reputation: 3419
Use Template.onCreated
to create reactiveVars
.
You must instantiate your reactiveVar before any controller code runs so that Tracker can correctly track your reactiveVar
. onRendered
is best used for functions that manipulate the DOM and runs too late to reliably ensure addingItem
exists when the helper runs, as you encountered.
That's what onCreated
is best for. That way your reactiveVar is ensured to exist when your helpers/controller code runs.
Template.AddingItem.onCreated(function() {
this.addingItem = new ReactiveVar(false)
})
And for future reference, Sessions
are actually just reactiveVars
with a global scope...there's nothing magical about them. It's reactiveVars
all the way down.
Upvotes: 1