在Meteor.js中将variables范围设置为模板

是否有可能创build一个variables范围的模板? 该variables可以在模板中的不同助手之间共享,但不在模板之外。

在下面这个例子中,如何在两个模板之间共享gamevariables而不重复其定义? 使用var进行初始化使其成为全局的,这不是我想要的。 谢谢!

 Template.userInfo.game = function() { var game = 'Angry Bird'; return game + ' game'; }; Template.userInfo.score = function() { var game = 'Angry Bird'; return game + ' score'; }; 

如果有人绊倒了这一点,并使用meteor1.0,这里是如何实现这一目标。

 Template.name.onCreated(function(){ this.data.variableName = "something"; }); Template.name.helpers({ 'helper' : function() { return Template.instance().data.variableName; } }); 

通过这种方式,variables的范围就是创build的模板的实例。 我有一个使用同一模板的多个实例的页面,所以这是非常有用的。

编辑:

所以这对于嵌套在另一个模板中的模板来说是完美的,但是对于父模板来说效果并不好。 data属性不是持有值,所以我做了一些更多的研究,发现在Template.onCreated的例子中,他们有this.highlightedPicture = new ReactiveVar(null); 所以显然可以在你的Template实例上定义新的属性。 我在两种情况下都尝试了这种方式,并使用Template.instance()

为什么不使用

 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) } }) 

您的私人_someVariable没有反应,它为这种情况下的选项服务。 但是你可以包装一个Deps.Dependency()来获得一个私有的反应模板的variables

从文档: http : //docs.meteor.com/#namespacing

只要声明一个变种,它将是文件范围。 没有这个variables,它将成为全球范围。

 var game = 'Angry Bird'; // File scope. game2 = 'Angry Bird'; // App scope. 

我有一些问题使用自动运行和variables范围,所以也许它会帮助某人:

 Template.foo.someHelper = function() { return this._someVariable } Template.foo.events({ "click #mylink": function(event, tmpl) { console.log(tmpl._someVariable) } }) Template.foo.onRendered(function() { this._someVariable = "some value" this.autorun(function(templateInstance) { Collection.find({}).fetch(); // Autorun will be executed each time this collection has change (update, delete, insert) console.log(templateInstance._someVariable); }, this.templateInstance()); }); 

你可以创build它作为一个反应variables在onCreated然后返回该variables在助手。 无论你set哪里setvariables,它都会自动更新帮手的值。 这是一个例子:

 Template.foo.onCreated(function() { this.yourVar = new ReactiveVar(""); this.yourVar.set("initValue"); }); Template.foo.helpers({ yourVar(){ return Template.instance().yourVar.get(); } }); Template.foo.events({ 'click .btn': function (event) { template.yourVar.set($(event.target).val()); } }); 

现在,您可以在模板中的任意位置调用{{yourVar}} ,并像上面一样编辑它的值。