我正在摸不着头脑,因为我记得在过去的某个时刻这个确切的代码正在工作。创建和呈现test
时,我设置this.data
的值,但我无法在事件或帮助程序中检索它。我开始认为包装或东西搞砸了我的Meteor。
<template name="test">
<button>click me</button>
</template>
Template.test.onCreated(function(){
// here I am setting the data context of the test template
this.data = {
doors: 5
};
// when I hover over `this` in Chrome is indeed shows the object
debugger
});
Template.test.onRendered(function(){
this.data = {
wheels: 4
};
// when I hover over `this` it also shows the object
debugger
var changeDataContext = function(obj){
this.data = obj;
};
changeDataContext( {engine: 1} );
// when I hover over `this` it shows the old value of `this`, not the new one with {engine: 1}
this;
debugger
});
Template.test.events({
'click button': function(e, tmpl){
tmpl;
// when I hover over `tmpl` it shows null for `data`???
debugger
}
});
Template.test.helpers({
images: function () {
this;
// when I hover over `this` it shows null for the value of `this`???
debugger
return this.wheels;
}
});
修改
这是一个概述问题的MeteorPad:
http://meteorpad.com/pad/Cqw3fWieJfspK2eYv/Leaderboard
在此查看调试器语句:
答案 0 :(得分:2)
这是您的示波器的问题。首先,对于onRendered
,您不能在函数中使用this
,并期望它在更高的范围内被视为this
:
Template.test.onRendered(function(){
this.data = {
wheels: 4
};
var self = this; // we save this scope's `this` for later
var changeDataContext = function(obj){
this.data = obj; // here, `this` refers to the current scope, ergo your changeDataContext function! onRendered's `this` does not get altered.
self.data = obj; // here, we refer to the `self` variable that you set earlier. It should work.
};
changeDataContext( {engine: 1} );
// tadaaaaaaaaaa
this;
debugger
});
然后,对于帮助者:this
代表数据上下文,而不是模板实例。如果您需要模板实例,请使用Template.instance()
:
Template.test.helpers({
images: function () {
var tmpl = Template.instance();
if (tmpl.data)
return tmpl.data.wheels;
}
});
请注意:数据上下文与<{1}}不同。您无法将内容放入Template.instance().data
this.data
中,并希望能够在您的Spacebars模板中使用它。为了方便起见,Iron路由器也将它存储在那里。
至于你的活动......那么它应该有效。你写的内容应该告诉你onCreated
。也许你事先以某种方式改变了你的实例wheels
?当然,您可以使用data
代替Template.instance()