Accessing parent class in Backbone

后端 未结 8 845
广开言路
广开言路 2020-12-07 14:40

I need to call the initialize method of the parent class, from inside the inherited MyModel-class, instead of completely overwriting it as I am doi

相关标签:
8条回答
  • 2020-12-07 15:02

    You might consider rewriting your code using functional inheritance.

    var BackBone=function(){
        var that={};
    
        that.m1=function(){
    
       };
       return that;
    
    };
    
    var MyModel=function(){
    
     var that=BackBone();
     var original_m1=that.m1;
    
    //overriding of m1
     that.m1=function(){
        //call original m1
     original_m1();
     //custom code for m1
      };
    };
    
    0 讨论(0)
  • 2020-12-07 15:07

    here's a multi generation callSuper method, just add it to your extending class.

    callSuper: function (methodName) {
        var previousSuperPrototype, fn, ret;
    
        if (this.currentSuperPrototype) {
            previousSuperPrototype = this.currentSuperPrototype;
            // Up we go
            this.currentSuperPrototype = this.currentSuperPrototype.constructor.__super__;
        } else {
            // First level, just to to the parent
            this.currentSuperPrototype = this.constructor.__super__;
            previousSuperPrototype = null;
        }
    
        fn = this.currentSuperPrototype[methodName];
    
        ret = (arguments.length > 1) ? fn.apply(this, Array.prototype.slice.call(arguments, 1)) : fn.call(this);
    
        this.currentSuperPrototype = previousSuperPrototype;
    
        return ret;
    }
    
    0 讨论(0)
  • 2020-12-07 15:09

    Similar to @wheresrhys, but I would use apply instead of call in case BaseModel.initialize is expecting arguments. I try to avoid processing the attributes map that can be passed to a Backbone Model upon initialization, but if the BaseModel were actually a View or a Collection then I might want to set options.

    var MyModel = BaseModel.extend({
        initialize: function() {
            this.constructor.__super__.initialize.apply(this, arguments);
            // Continue doing specific stuff for this child-class.
        },
    });
    
    0 讨论(0)
  • 2020-12-07 15:13

    This worked for me, when I was trying to inherit among my models:

    MyModel.prototype.initialize.call(this, options);
    

    Referenced from http://documentcloud.github.com/backbone/#Model-extend

    Thanks.

    0 讨论(0)
  • 2020-12-07 15:14
    MyModel = BaseModel.extend({
        initialize: function() {
            MyModel.__super__.initialize.apply(this, arguments);
            // Continue doing specific stuff for this child-class.
        },
    });
    
    0 讨论(0)
  • 2020-12-07 15:16

    this seems to be almost a duplicate of Super in Backbone, so you want something like this:

    Backbone.Model.prototype.initialize.call(this);
    
    0 讨论(0)
提交回复
热议问题