将Backbone.View重新注入DOM,保留事件而不是创建新事件



我得到了以下示例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/

您正试图绑定到Backbone视图而不是DOM元素:

this.on('switch', this.switch, this);

这一切都很好,但谁触发了"切换"事件?您没有触发DOM事件的绑定,this.delegateEvents();仅适用于DOM事件。

一旦设置了DOM事件,例如

this.$el.on('click', 'a', this.switch)--"switch"事件将被触发,并且只要$el未从DOM中删除,就不必重新委托事件。

最新更新