2013-05-17 34 views
0

我正在呈現集合中的每個項目的視圖,每個項目都包含一個列表,我試圖追加到一個ul,但他們正在附加到其他視圖的ul。嘗試追加到當前視圖中的類,但導致追加到其他視圖

查看:

initialize: function(){ 

    }, 

    render: function(){ 
     var current = this.model.toJSON(); 
     this.$el.html(_.template(cTemplate, current)); 

     var items = this.model.toJSON().items; 
     items.forEach(function(item){ 
      this.$('.list').append('<li>'+item.attributes.price+'</li>'); 
     }); 

     return this; 
    } 

模板:

<ul class="list"></ul> 

我想追加到此$( '名單。')我本以爲這意味着我追加每個項目的價格僅限於當前視圖中我的模板類。看起來我不能像這樣引用它,因爲價格被追加到當前渲染前的視圖中的所有列表類中。

我想知道如何防止追加到同一頁上的所有相同的類,只是從當前視圖的模板中追加。

+0

注意:如果items是一個數組,那麼'foreach'函數中的'this'不會是您的視圖,而是一個窗口。所以這個。$是全球jQuery! –

回答

0

如果ul是這個視圖類的tagName,你可以簡單地追加到這個。

items.forEach(function(item){ 
    this.$el.append('<li>'+item.attributes.price+'</li>'); 
}); 

,或者ul.list是一個子元素,你可以做到這一點

items.forEach(function(item){ 
    this.$el.find('ul.list').append('<li>'+item.attributes.price+'</li>'); 
}); 

注意:當複雜性增加這種模式可能不會在將來維護。如果這些項目有交互作用,您可以考慮爲每個項目創建單獨的視圖。