1

是否可以创建一组存在于每个视图中的默认事件?例如,如果我的应用程序中的每个视图都包含一个设置按钮

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

如何将此事件打包以包含在我的应用程序的每个视图中?

4

2 回答 2

4

问题是它View#extend只是覆盖现有属性,因此您不能将您的属性放入'click #settings'基类和子类中。但是,您可以轻松地用extend您自己的东西来替换events。像这样的东西:

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

您可以使用事件和函数创建一个基本视图,然后让您的其他视图继承它。我喜欢这里描述的模式,因为它很容易设置并且可以根据需要轻松覆盖:http ://www.scottlogic.com/blog/2012/12/14/view-inheritance-in-backbone.html

基本视图如下所示:

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 回答