2012-10-26 86 views
12

我開始使用流星,並且使todo example包含嵌套標記組。我有以下的HTML,它輸出每個標籤組的每一個名字,加上標記,各組名單:流星:如何訪問嵌套模板中的父屬性?

<template name="tag_filter"> 
    {{#each tag_types }} 
     {{ tag_name }} 
     {{#each values }} 
     <div data-taggroup="{{ ../tag_name }}"> 
     {{ name }} ({{ count }}) 
     </div> 
     {{/each}} 
    {{/each}} 
</template> 

我的問題是:我怎麼適應的事件處理程序上的標籤點擊訪問父組的tag_name的值? (即來自每個外部循環的數據)。

目前我有下面的代碼,但this對象只給我訪問namecount

Template.tag_filter.events({ 
    'mousedown .tag': function() { 
    console.log('tag mousedown', this); 
    // How do I get the value of tag_name? 
    } 
}); 

正如你所看到的,我用Handlebars parent paths添加包含名稱的data-taggroup屬性,但我不知道如何訪問從事件處理程序中。

我認爲this question是相關的,但我不明白OP的解決方案(部分原因是因爲我沒有使用Coffeescript)。還有一個相關的closed Meteor issue

回答

3

我不確定您是否可以獲取父模板數據,但是在您的事件處理程序中,您可以訪問DOM元素:event.currentTarget將獲取單擊的元素。然後只需使用jQuery來訪問屬性。如果需要,event.currentTarget.parentNode將獲得DOM中的父元素。例如:我不知道你放置標籤類的位置,但假設它是你的div類,其中定義了數據標籤組。然後,你可以使用取得標籤名稱:

$(event.currentTarget).attr('data-taggroup') 
10

我找到了解決訪問父數據:

Template.nestedTemplate.events({ 
    'click a.class':function(event,template){ 
     var parentID = template.data._id; 
     console.log(parentID); 
    } 
}); 

的.events處理函數接收兩個參數:事件,與有關事件的信息的對象,以及模板,模板是定義處理程序的模板的模板實例。花了我很長時間來弄清楚這一點。不要使用車把解決方案,它會顯示您的數據!

+1

只有當前數據上下文具有該變量集時,_id'纔會存在。這和調用'this._id'是一樣的。我不知道如何讓你訪問父母的數據? –

+4

這個。會得到當前的上下文(例如,如果你在{{each}}塊中),對於我'template'獲取模板上下文,它可以與當前上下文不同。 –

0
"click selected":function(e){ 
    // this._id 
    var doc_id = $(e.currentTarget).parent().parent().attr("uid") 
    console.log(doc_id) 
}, 
//specify the each id in the div above the nearest #each 
//this will work in events but not in helpers`