次の例の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()を使用してすべてのイベントバインディングを再作成します。これは実際には完璧な解決策ではありません...これを使用するとはるかに良いでしょう。$el.detach(); または他のメソッドなので、すべてのイベントを再レンダリングして再作成するのではなく、オブジェクト全体をそのイベントとともにキャッシュします。
現在、フィドルが機能しています:http: //jsfiddle.net/RRXnK/66/