Backbone View: Inherit and extend events from parent

前端 未结 15 628
醉梦人生
醉梦人生 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:30

    Short version of @soldier.moth's last suggestion:

    var ChildView = ParentView.extend({
      events: function(){
        return _.extend({}, _.result(ParentView.prototype, 'events') || {}, {
          'click' : 'onclickChild'
        });
      }
    });
    
    0 讨论(0)
  • 2020-11-30 17:30

    This CoffeeScript solution worked for me (and takes into account @soldier.moth's suggestion):

    class ParentView extends Backbone.View
      events: ->
        'foo' : 'doSomething'
    
    class ChildView extends ParentView
      events: ->
        _.extend({}, _.result(ParentView.prototype, 'events') || {},
          'bar' : 'doOtherThing')
    
    0 讨论(0)
  • 2020-11-30 17:31

    This would also work:

    class ParentView extends Backbone.View
      events: ->
        'foo' : 'doSomething'
    
    class ChildView extends ParentView
      events: ->
        _.extend({}, _.result(_super::, 'events') || {},
          'bar' : 'doOtherThing')
    

    Using straight super wasn't working for me, either was manually specifying the ParentView or inherited class.

    Access to the _super var which is available within any coffeescript Class … extends …

    0 讨论(0)
  • 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);
        };
      }
    });
    
    0 讨论(0)
  • 2020-11-30 17:33

    You could also use the defaults method to avoid creating the empty object {}.

    var ChildView = ParentView.extend({
      events: function(){
        return _.defaults({
          'click' : 'onclickChild'
        }, ParentView.prototype.events);
      }
    });
    
    0 讨论(0)
  • 2020-11-30 17:34

    If you use CoffeeScript and set a function to events, you can use super.

    class ParentView extends Backbone.View
      events: ->
        'foo' : 'doSomething'
    
    class ChildView extends ParentView
      events: ->
        _.extend {}, super,
          'bar' : 'doOtherThing'
    
    0 讨论(0)
提交回复
热议问题