Backbone View: Inherit and extend events from parent

前端 未结 15 799
醉梦人生
醉梦人生 2020-11-30 16:50

Backbone\'s documentation states:

The events property may also be defined as a function that returns an events hash, to make it easier to programmatic

15条回答
  •  难免孤独
    2020-11-30 17:32

    To do this entirely in the parent class and support a function-based events hash in the child class so that children can be agnostic of inheritance (the child will have to call MyView.prototype.initialize if it overrides initialize):

    var MyView = Backbone.View.extend({
      events: { /* ... */ },
    
      initialize: function(settings)
      {
        var origChildEvents = this.events;
        this.events = function() {
          var childEvents = origChildEvents;
          if(_.isFunction(childEvents))
             childEvents = childEvents.call(this);
          return _.extend({}, MyView.prototype.events, childEvents);
        };
      }
    });
    

提交回复
热议问题