2012-02-27 41 views
0

我有一個使用的CollectionView輸出以下一個backbone.marionette應用:使用CollectionView創建同級項目視圖?

  • 的div#主.widget
    • div.head
    • div.body

以下是2個兄弟姐妹ItemViews:

var LogLocationBodyView = App.ItemView.extend({ 
    tagName: "div", 
    attributes: {class: "body"}, 
    template: "#log-location-body-template" 
}); 

var LogLocationHeadView = App.ItemView.extend({ 
    tagName: "div", 
    attributes: {class: "head"}, 
    template: "#log-location-head-template" 
}); 

這裏是的CollectionView:

var LogLocationsView = App.CollectionView.extend({ 
    template: "#log-locations-template", 
    attributes: {id: "main", class: "widget"}, 
    itemView: LogLocationHeadView 
}); 

我能明顯得到LogLocationHeadView渲染,但我在尋找到inserAfter()LogLocationBodyView最好的方法,使2個ItemViews都是兄弟姐妹。

什麼是最好的方法來解決這個問題?我嘗試了許多不同的方法。首先,我嘗試使用ItemView的onRender(),但很快意識到我只能追加到視圖中的標記。我真的需要insertAfter()並且父類不可用,因爲在onRender中,我們仍然是在DOM之前的插入。

var LogLocationHeadView = App.ItemView.extend({ 
    tagName: "div", 
    attributes: {class: "head"}, 
    template: "#log-location-head-template", 
    onRender: function() { 

     // create a new piece of html from a different template 
     var view = new LogLocationBodyView({ 
      model: this.model 
     }); 

     view.render(); 

     $(this.el).append(view.el); 

     var c = $(this.el).children(); 
      console.log(c); // true 

     var p = $(this.el).parents(); 
      console.log(p); //undefined 

    } 

我也明白,我可以在CollectionViews覆蓋appendHTML()和renderItem()方法,但我需要仍然能夠追加()。所以我需要能夠傳遞一個renderType。

我真正想要做的是傳遞一個ItemViews數組和renderType到renderItem。然後,renderItems可以在appendHTML()內分叉。

var LogLocationsView = App.CollectionView.extend({ 
    template: "#log-locations-template", 
    attributes: {id: "main", class: "widget"}, 
    itemViews: [{view: LogLocationHeadView, renderType: append}, {view: LogLocationBodyView, renderType: insertAfter}] 
}); 

在我試圖做到這一點之前,我想看看我是否完全脫離了這裏的基地。有一個更好的方法嗎?

回答

0

做到這一點的最好和最乾淨的方法是將父視圖的標題和正文視圖追加這兩個視圖在其render方法,而不必依靠insertAfter。如果您希望從視圖中處理它尚未插入的視圖,但會在當前瀏覽器事件循環結束時繼續使用下劃線defer方法或setTimeout(fn, 1)方法。

和btw。如果它是div,則不需要指定tagName,因爲div是tagName的默認值。

相關問題