2013-06-25 85 views
-1

我使用流星0.6.4。我的问题是,呈现的模板的数据上下文时有时未定义,因此,“这”目的是窗口的引用:为什么流星模板onRendered Function中的'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代码被包裹的{{每个}}车把内声明:

<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'作为Window调用的函数。

回答

-1

模板助手里面的this将始终指向window对象。

您可以在Template.rendered()或事件处理函数中访问data上下文。在事件处理程序中,它作为第二个参数传递,如function(event, template),其中template是当前模板对象。

但是,我建议您使用模板实例功能,如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 
    } 
} 
+0

模板内的'this'对象'onRendered'回调函数是对与该函数关联的模板实例的引用。查看[流星文档](http://docs.meteor.com/#/full/template_onRendered)了解'onRendered'模板回调函数的更多细节。 – n4tiv3pwnst4r

0

您应该使用template.xxx.helpers代替,即:

Template.task.helpers({ 
    nDate: function() { 
    return this.due_date.getTime(); 
    } 
}); 

当你的助手中使用它,这就是数据上下文。

0

我使用'帮手'功能,我有同样的问题。 “这”对象有时是窗口对象:

Template.task.helpers({ 
... 
    'time_left': function(){ 
     debugger; 
     var nDate = this.due_date.getTime(); 
... 
0

当使用任何的三个流星模板回调函数,包括onRendered功能,this对象实际上是一个模板实例对象。虽然可以通过此对象检索模板的数据上下文,但建议您通过使用Template.currentData()函数来引用模板数据上下文。该功能的文档可以在here找到。