2015-08-13 20 views
0

我想從事件處理程序訪問我的模板的數據上下文,但它是空的。模板事件處理程序的流星數據上下文爲空

這裏是我的模板:

<template name="calendar"> 
    <div class="calendar"> 
    {{#with calendar}} 
     <h1>{{name}}</h1> 
     {{#each days}} 

     <div class="calendar-day"> 
      {{this.date.getDate}} 
<!-- I want to access the data context when this div is pressed --> 
     </div> 

     {{/each}} 
    {{/with}} 
    </div> 
</template> 

這裏就是我想要得到的數據上下文。

Template.calendar.events({ 
    'click .calendar-day': function(e, template) { 
    console.log(Template.currentData()); // null 
    console.log(Template.parentData()); // null 
    } 
}); 

更新:我能夠通過this訪問當前的數據上下文,但我也想訪問父的數據上下文,即對calendar

回答

0

數據上下文可以獲取上下文從this

Template.calendar.events({ 
    'click .calendar-day': function(e, template) { 
    console.log(this); 
    } 
}); 
+0

但是我如何訪問父級的數據上下文? – harinsa

1

好的。讓我說清楚;

Template.calendar.events({ 
    'click .calendar-day': function(e, template) { 
    //FYI: template === Template.instance() 

    //will give you your data context 
    console.log(this); 

    //will give you your data context 
    console.log(template.data); 

    //will give you your data context 
    console.log(Template.currentData()); 

    //will give you your data context also 
    console.log(Template.parentData(0)); 

    //will give you your parent template data context. Equivalent of Template.parentData() 
    console.log(Template.parentData(1)); 

    } 
}); 

如果事實證明你的parentData是null那麼它是null,仔細檢查它。

+0

我的問題與OP完全相同,並且幾乎相同。我在{{#with}}範圍內的{{#each}}中有一個事件。但是,儘管'this'被正確設置爲#each的上下文,但template.data爲空,所有其他上下文都如上所述。我完全被這個困惑 - 無論其他可能的上下文,爲什麼template.data爲空? –

+0

我已修復它 - 或者至少建立了解決方法。我在這個帖子上發佈了一個具體的答案來解釋 –

0

Blaze中可能存在一個bug - github有3個或4個與此有關的公開問題,所以我沒有提出具體的問題。

問題在於在單個模板中有多個數據上下文;此修復程序是通過拆分模板分裂上下文:

<template name="calendar"> 
    <div class="calendar"> 
    {{#with calendar}} 
     <h1>{{name}}</h1> 
     {{#each days}} 
     {{> calendarDay}} 
     {{/each}} 
    {{/with}} 
    </div> 
</template> 

<template name="calendarDay"> 
    <div class="calendar-day"> 
    {{this.date.getDate}} 
    <!-- I want to access the data context when this div is pressed --> 
    </div> 
</template> 

然後只要將您的活動,新的模板:

Template.calendarDay.events({ 
    'click .calendar-day': function(e, template) { 
    console.log(Template.currentData()); // no longer null! 
    console.log(Template.parentData()); // no longer null! 
    } 
}); 

在這種情況下,你現在可以得到以下數據上下文:

console.log(this);     // the {{#each days}} context 
console.log(template.data);   // the {{#each days}} context 
console.log(Template.currentData()); // the {{#each days}} context 
console.log(Template.parentData(0)); // the {{#each days}} context 
console.log(Template.parentData(1)); // the {{#with calendar}} context 

通過使用所描述的我已經成功地解決了一個相同的問題的任擇議定書,但只有2-3個小時的排查這種模式!

相關問題