1

すべてのビューに存在する一連のデフォルト イベントを作成することは可能ですか? たとえば、アプリケーションのすべてのビューに設定ボタンが含まれている場合

        events: {
            "click #settings" : "goSettings"
        },
        ...
        goSettings: function() {
            // settings show function
        });

このイベントをパッケージ化して、アプリケーションのすべてのビューに含めるにはどうすればよいですか?

4

2 に答える 2

4

問題は、既存のプロパティを単純に上書きするため、基本クラスとサブクラスにView#extend配置できないことです。ただし、マージする独自のものに'click #settings'簡単に置き換えることができます。このようなもの:extendevents

var B = Backbone.View.extend({
    events: {
        'click #settings': 'goSettings'
    }
}, {
    extend: function(properties, classProperties) {
        properties.events = _({}).extend(
            properties.events || { },
            this.prototype.events
        );
        return Backbone.View.extend.call(this, properties, classProperties);
    }
});

そして、ビューBの代わりに拡張Backbone.Viewします。

デモ: http://jsfiddle.net/ambiguous/Kgh3V/

于 2013-11-09T01:56:02.300 に答える
2

イベントと関数を使用して基本ビューを作成し、それから他のビューを継承させることができます。セットアップが簡単で、必要に応じて簡単にオーバーライドできるため、ここで説明するパターンが気に入っています

ベース ビューは次のようになります。

var BaseSearchView = function(options) {
  this.inheritedEvents = [];
  Backbone.View.call(this, options);
}

_.extend(BaseView.prototype, Backbone.View.prototype, {
  baseEvents: {},

  initialize: function(options) {
    // generic initialization here
    this.addEvents({
      "click #settings" : "goSettings"
    });
    this.initializeInternal(options);
  },

  render: function() {
    // generic render here
    this.renderInternal();
    return this;
  },

  events: function() {
    var e = _.extend({}, this.baseEvents);
    _.each(this.inheritedEvents, function(events) {
      e = _.extend(e, events);
    });
    return e;
  },

  addEvents: function(eventObj) {
    this.inheritedEvents.push(eventObj);
  },

  goSettings: function() {
        // settings show function
  }
});

BaseView.extend = Backbone.View.extend;

そして、あなたの子クラスは次のようになります:

var MyView = BaseView.extend({

  initializeInternal: function(options) {
    // do something
    // add event just for this child
    this.addEvents({
      "click #differentSettings" : "goSettings"
    });

  },
  renderInternal: function() {
    // do something
  }
});
于 2013-11-09T01:58:20.513 に答える