我得到了以下示例 Backbone.View:
var View = Backbone.View.extend({
tagName: "div",
className: "advertisement",
initialize: function () {
this.on('switch', this.
switch, this);
this.views = {};
this.views.laptop = new LaptopAdView();
this.views.piano = new PianoAdView();
this.views.food = new FoodAdView();
},
render: function () {
this.$el.empty();
this.
switch ('laptops');
return this;
},
switch: function (ad) {
var el;
if (ad === 'laptop') {
el = this.views.laptop.render().el;
} else if (ad === 'piano') {
el = this.views.piano.render().el;
} else {
el = this.views.food.render().el;
}
// reinsert the chosen view
this.$el.empty().append(el);
// bind all events new
this.delegateEvents();
}
});
如您所见,我使用 this.delegatEvents() 重新创建所有事件绑定。这实际上不是一个完美的解决方案......当我使用 this.$el.detach(); 会好得多 或其他方法,因此我使用其事件缓存整个对象,而不是重新渲染和重新创建所有事件。
现在使用小提琴:http: //jsfiddle.net/RRXnK/66/