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

后端 未结 3 1019
执笔经年
执笔经年 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:18

    Actually, I'dont know if this solves your case, but I usually do this: this.constructor.__super__.initialize.apply(this, arguments); and works like a charm. My solution is completely wrong. Here's why:

    var Model1 = Backbone.Model.extend({
      method: function () {
        // does somehting cool with `this`
      }
    });
    
    var Model2 = Model1.extend({
      method: function () {
        this.constructor.__super__.method.call(this);
      }
    });
    
    var Model3 = Model2.extend({
      method: function () {
        this.constructor.__super__.method.call(this);
      }
    });
    
    var tester = new Model3();
    
    // Boom! Say hallo to my little stack-overflowing recursive __super__ call!
    tester.method();
    

    The call to this.constructor.__super__ in Model2::method will resolve to (drum-roll) Model2::method.

    Always use ExplicitClassName.__super__.methodName.call(this, arg1, arg2 /*...*/) or Coffee-script's super.

提交回复
热议问题