为什么是';这';在Meteor模板中,呈现函数未定义?
我用的是流星0.6.4。我遇到的问题是,呈现模板时的数据上下文有时是未定义的,因此,“this”对象是对窗口的引用:为什么是';这';在Meteor模板中,呈现函数未定义?,meteor,this,Meteor,This,我用的是流星0.6.4。我遇到的问题是,呈现模板时的数据上下文有时是未定义的,因此,“this”对象是对窗口的引用: Template.task.time_left = function(){ debugger; var nDate = this.due_date.getTime(); Exception from Deps recompute: TypeError: Cannot call method 'getTime' of undefined html代码包装在{{e
Template.task.time_left = function(){
debugger;
var nDate = this.due_date.getTime();
Exception from Deps recompute: TypeError: Cannot call method 'getTime' of undefined
html代码包装在{{each}}handlebar语句中:
<template name="tasks_lists">
{{#each tasks_list}}
...
{{#each task}}
{{> task}}
{{/each}}
...
{{/each}}
</template>
<template name="task">
...
<div class="text">{{due_date}}</div>
...
</template>
{{{#每个任务列表}
...
{{{#每个任务}
{{>任务}
{{/每个}}
...
{{/每个}}
...
{{到期日}
...
我读到这个错误在早期版本的Meteor中得到了解决。如何避免使用“this”作为窗口调用函数。模板帮助程序中的
this
始终指向窗口
对象
您可以访问Template.rendered()
或事件处理程序函数中的数据
上下文。在事件处理程序中,它作为第二个参数作为函数(事件,模板)
传递,其中模板
是当前模板对象
但是,我建议您使用模板实例函数,例如find()、findAll()、firstNode()、lastNode()
,而不是数据上下文
Template.task.rendered = function() {
if( !this.window ){ //check that 'this' is not a 'window' object
var el = this.find( 'div.text' ); // the div that holds due_date
//do something
}
}
您应该改用template.xxx.helpers,即:
Template.task.helpers({
nDate: function() {
return this.due_date.getTime();
}
});
当您在helpers中使用它时,这就是数据上下文。我使用了“helpers”函数,我也有同样的问题。”此对象有时是窗口对象:
Template.task.rendered = function() {
if( !this.window ){ //check that 'this' is not a 'window' object
var el = this.find( 'div.text' ); // the div that holds due_date
//do something
}
}
Template.task.helpers({
...
'time_left': function(){
debugger;
var nDate = this.due_date.getTime();
...
当使用三个Meteor模板回调函数(包括
onRendered
函数)中的任何一个时,此
对象实际上是一个模板实例对象。尽管可以通过此对象检索模板的数据上下文,但建议您通过使用template.currentData()
函数来引用模板数据上下文。可以找到此函数的文档。模板onRendered
回调函数中的this
对象是对与该函数关联的模板实例的引用。有关onRendered
模板回调函数的更多详细信息,请参阅。