如果您实际上没有看到性能问题,我不会过度优化。处理ItemView
事件,因为这是有道理的。
如果您已经知道性能/内存问题,或者您遇到了一个问题,那么您的两个选项的组合可能是要走的路:ItemView
处理事件,但听parent 中的事件ListView
。这将要求您跟踪您的子视图
因此,如果您ItemView
目前看起来像这样:
var ItemView = Backbone.View.extend({
events: {
"click .submit" : "onSubmitClicked"
},
onSubmitClicked: function() {
//...
}
});
你可以像这样重构它:
var ItemView = Backbone.View.extend({
//give item a css class to scope the events
cssClass: "item-view",
initialize: function() {
//set id attribute to the DOM element
this.attributes["data-id"] = this.model.id;
},
onSubmitClicked: function() {
//...
}
});
并在列表视图中监听冒泡事件,并将它们代理到项目视图:
var Listview = Backbone.View.extend({
events: {
//scope child events by css class
"click .item-view .submit" : "onItemSubmitClicked"
},
render function() {
var childViews = this._childViews = {};
this.collection.each(function(model) {
//render the child views any way you want
var itemView = new ItemView({model:model}).render();
//keep a id->view map
childViews[model.id] = itemView;
});
},
//proxy events to the correct childview
onItemSubmitClicked: function(event) {
var itemView = this._childViews[$(event.target).attr('data-id')];
itemView.onSubmitClicked(event);
}
});
我以这种方式轻松地重构了现有视图,因为事件处理程序保持原样,并且只有侦听器代码被提升了一个档次。它确实带来了复杂性开销,但如果您需要优化性能,通常必须付出一些代价。