2013-06-25 83 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找到。