我想知道 Backbone.js 中用于管理集合中的子模型视图的一些一般最佳实践。
迄今为止,我一直在使用下面的解决方案。只是想知道是否有其他人对此有所了解,或者有更好的处理方式。到目前为止,它对我来说效果很好,但我总是有兴趣了解更多和改进我的代码。
CollectionView = Backbone.View.extend({
renderItem: function(model) { // instantiate view for an item
this.viewPointers[model.cid] = new this.itemView({ model: model });
this.$(".item-list").append( this.viewPointers[model.cid].render().el );
},
renderCollection: function() { // instantiate views for entire collection
var self = this;
this.removeAll(); // clear current references (if any exist)
this.collection.each(function(model){
self.renderItem(model);
});
},
removeItem: function(model) { // remove/delete an individual view object
this.viewPointers[model.cid].undelegateEvents();
this.viewPointers[model.cid].remove();
delete this.viewPointers[model.cid];
},
removeAll: function() { // remove/delete entire collection's view objects
var self = this;
_.each(this.viewPointers, function(view) {
self.removeItem(view.model);
});
}
});
我通常通过扩展 CollectionView 类来实现这一点。就像是
MyView = CollectionView.extend({
el: '#id',
viewPointers: {}, // reference to individual itemViews by model CID
itemView: views.SingleItem,
...
initialize: function() {
this.renderCollection();
},
});
有没有其他人有他们喜欢在这种情况下使用的东西?