backbone.js view inheritance. `this` resolution in parent

后端 未结 3 1020
执笔经年
执笔经年 2021-02-01 10:59

I have a case that uses view inheritance, and my code looks essentially like:

parentView = Backbone.View.extend({
    events: {
        \"some event\": \"busines         


        
3条回答
  •  死守一世寂寞
    2021-02-01 11:21

    Have you tried extending this.events in the constructor, instead of in the initialize function? If you do this in initialize, you're too late; event delegation for the business function has already been setup in the constructor, and will point to parentView (see the call to this.delegateEvents(); in Backbone.View's constructor).

    Updated with a working example:

    ParentView = Backbone.View.extend({
        name: 'ParentView',
        events: {
            "event": "business"
        },
        business: function(e){
            this.someFunc && this.someFunc();
        }
    });
    
    ChildView = ParentView.extend({
        name: 'ChildView',
        events: {
        },
        constructor: function(){
           this.events = _.extend( {}, ParentView.prototype.events, this.events );
           console.debug( this.events );
           ParentView.prototype.constructor.apply( this, arguments );
        },
        someFunc: function(){
            console.debug('someFunc; this.name=%s', this.name);
        }
    });
    
    child = new ChildView();
    $( child.el ).trigger('event');
    // logs 'this' in 'someFunc'; the name is 'ChildView'.
    

提交回复
热议问题