2016-05-04 176 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