为什么我的流星模板上下文数据没有被保存
Why is my Meteor template context data not being saved?
我对此感到挠头,因为我记得这段代码在过去的某个时候是工作的。当创建和渲染test
时,我设置了this.data
的值,但我无法在事件或帮助程序中检索它。我开始认为是一个包裹或什么东西把我的流星搞砸了。
<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查看调试器语句:
http://app-5p5urzku.meteorpad.com/这是作用域的问题。首先,对于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;
}
});
请注意:数据上下文与Template.instance().data
的不同。你不能把东西放进onCreated
的this.data
,并期望能够在你的空格模板中使用它。铁路由器只是为了方便而把它储存在那里。
关于你的事件…好了,应该可以了。你所写的应该显示你的wheels
。也许你是改变你的实例的data
在某种程度上事先?当然,您可以使用Template.instance()
来代替tmpl
相关文章:
- 如何在服务器上保存数据以备日后使用
- zp.midpass.ru如何在浏览器中保存数据
- Google Chrome扩展在本地保存数据
- Javascript/AngularJS本地保存数据
- jquery ajax到php脚本不保存数据
- 使用LocalStorage保存数据
- jquery保存数据,直到phonegap应用程序关闭
- 以HTML和javascript保存数据
- 单击指向外部网站的链接后,通过MySQL保存数据
- AngularJS:无法保存数据
- 如何在不编码或保存数据的情况下将二进制数据从javascript传递到actionscript(网页到flash)
- 如何在AngularJS中刷新时在服务中持久保存数据
- 如果从浏览器控制台提交,Knockoutjs不会保存数据
- 在nodejs中执行procces数组时保存数据
- MongoDB 在保存数据时抛出错误(拓扑已损坏)
- HTML 在表单之间保存数据
- HTML/JS - 保存数据-* 供以后使用
- 保存数据 asp.net 后单击按钮时显示警报消息
- Chrome 扩展程序保存数据
- 如何在应用程序上保存数据