Is it possible to create a variable that is scoped to a template? This variable can be shared among the different helpers in the template, but does not exist outside of the template.
In this example below, how can game
variable be shared between the 2 templates without repeating its definition? Initializing it using var
makes it global which is not what I want. Thank you!
Template.userInfo.game = function() {
var game = 'Angry Bird';
return game + ' game';
};
Template.userInfo.score = function() {
var game = 'Angry Bird';
return game + ' score';
};
If anyone else stumbles across this and is using Meteor 1.0, here's how you can achieve this.
Template.name.onCreated(function(){
this.data.variableName = "something";
});
Template.name.helpers({
'helper' : function() {
return Template.instance().data.variableName;
}
});
This way the variable is scoped to the instance of the template that was created. I have a page that uses multiple instance of the same template so this was very useful.
EDIT:
So this worked perfectly for templates nested inside another template, but didn't work so well with the parent template. The data
property wasn't holding values so I did some more research and found this in the example for Template.onCreated
they have this.highlightedPicture = new ReactiveVar(null);
so apparently it's fine to define new properties on your Template instance. I tried this in both scenarios and it works great with Template.instance()
.
Why don't use
Template.foo.created = function() {
this._someVariable = "some value"
}
Template.foo.someHelper = function() {
return this._someVariable
}
Template.foo.events({
"click #mylink": function(event, tmpl) {
console.log(tmpl._someVariable)
}
})
Your private _someVariable
is not reactive it serves for options in this case. But you can wrap a Deps.Dependency()
to get a private reactive Template's variables
From the docs: http://docs.meteor.com/#namespacing
Just declare it with a var and it will be file scope. Without the var it will be global scope.
var game = 'Angry Bird'; // File scope.
game2 = 'Angry Bird'; // App scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With