Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a Variable Scope to Template in Meteor.js

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';
};
like image 790
Nyxynyx Avatar asked Nov 21 '13 19:11

Nyxynyx


3 Answers

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().

like image 108
Shaded Avatar answered Oct 23 '22 02:10

Shaded


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

like image 43
Roman Avatar answered Oct 23 '22 04:10

Roman


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.
like image 44
pstuart2 Avatar answered Oct 23 '22 02:10

pstuart2