Backbone View: Inherit and extend events from parent

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

    A pattern for this that I am fond of is modifying the constructor and adding some additional functionality:

    // App View
    var AppView = Backbone.View.extend({
    
        constructor: function(){
            this.events = _.result(this, 'events', {});
            Backbone.View.apply(this, arguments);
        },
    
        _superEvents: function(events){
            var sooper = _.result(this.constructor.__super__, 'events', {});
            return _.extend({}, sooper, events);
        }
    
    });
    
    // Parent View
    var ParentView = AppView.extend({
    
        events: {
            'click': 'onclick'
        }
    
    });
    
    // Child View
    var ChildView = ParentView.extend({
    
        events: function(){
            return this._superEvents({
                'click' : 'onclickChild'
            });
        }
    
    });
    

    I prefer this method because you do not have to identify the parent -one less variable to change. I use the same logic for attributes and defaults.

提交回复
热议问题