2016-05-04 177 views
1

交換childview是否可以動態地改變childView中的CollectionView木偶,在collectionVeiw

類似:

//model 
    var FooBar = Backbone.Model.extend({ 
     selected: false, 
    }); 



    //collection view 
    var MyCollectionView = Marionette.CollectionView.extend({ 
      getChildView: function(item) {  
      if (item.selected === true) { 
       return FooView; 
      } 
      else { 
       return BarView; 
      } 
      }, 

      // trigger from child view that should swap views 
      // model.selected is now true 
     triggerFromChildView: function (childview, model) { 
      //how to destroy childview and to re-create one for this model? 
     } 
    }); 

回答

1

你基本上得到它,但爲了確保新的視圖被創建和正確渲染,您需要重新渲染整個集合視圖。

1.)您可以偵聽childView事件並在childView模型更改時重新呈現collectionView。有可能是這樣做更有效的方式,但是這將工作:

var FooView = Marionette.ItemView.extend({ 
    initialize: function() { 
    this.listenTo(this.model, 'change', function(){ 
     this.trigger('item:model:change'); 
    }); 
    } 
}); 

// get the collection view in place 
var MyCollectionView = new CollectionView({ 
    getChildView: ...  
    //bind the function to the scope of the collection view 
    onChildviewItemModelChange: _.bind(function() { 
    this.render(); 
    },this) 
}); 

2)您也可以嘗試removeChildView和的addChild ...但是這牽涉到你所需要管理更多的運動件。如果您正在處理一個相對較小的列表,重新渲染整個事件不會損害性能。

3)另一種選擇是,當模型發生變化,只是collection.reset(data),然後確保你在你的CollectionView this.listenTo(this.collection, 'reset', this.render);

+0

謝謝你的想法。我的第一個想法是「複製」刪除模型(沉默),然後再將該模型添加到集合中(這將觸發渲染,並且比較器將新視圖放置在舊模型的相同位置) – InTry