2012-01-23 14 views
67

Necesito llamar al método initialize de la clase padre, desde el MyModel -class heredado, en lugar de sobrescribirlo por completo como lo estoy haciendo hoy.Accediendo a la clase principal en Backbone

¿Cómo podría hacer esto?

Aquí es lo que mi código es ahora:

BaseModel = Backbone.Model.extend({ 
    initialize: function(attributes, options) { 
     // Do parent stuff stuff 
    } 
}); 

MyModel = BaseModel.extend({ 
    initialize: function() { 
     // Invoke BaseModel.initialize(); 
     // Continue doing specific stuff for this child-class. 
    }, 
}); 

Respuesta

50
MyModel = BaseModel.extend({ 
    initialize: function() { 
     MyModel.__super__.initialize.apply(this, arguments); 
     // Continue doing specific stuff for this child-class. 
    }, 
}); 
+0

Hola Raynos - Eso arroja un error de "demasiada recursividad" en la consola. – Industrial

+1

@Industrial, entonces está haciendo algo tonto. Pruebe 'this .__ super __. Initialize.apply (this, arguments);' – Raynos

+5

'__ super __' no está destinado a usarlo directamente, como lo implica el nombre subrayado. –

5

creo que sería

MyModel = BaseModel.extend({ 
    initialize: function() { 
     this.constructor.__super__.initialize.call(this); 
     // Continue doing specific stuff for this child-class. 
    }, 
}); 
+0

Es 'este .__ súper __ initialize.call (this);..' – Raynos

+0

Tanto 'este .__ súper __ prototype.initialize.call (this);' y 'este .__ súper __ initialize.call (esto).; 'throws' this .__ super__ no está definido' en Firebug. – Industrial

+0

ninguno de ellos está funcionando :( –

-4

usted podría considerar volver a escribir el código utilizando la herencia funcional.

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

dudo que la reescritura de la red troncal esté en orden aquí :) tenemos que gestionar con la estructura que nos proporciona la columna vertebral, y hay soluciones mucho mejores que reescribir todo esto, como el __super__ es más que suficiente. – Sander

125

Trate

MyModel = BaseModel.extend({ 
    initialize: function() { 
     BaseModel.prototype.initialize.apply(this, arguments); 
     // Continue doing specific stuff for this child-class. 
    }, 
}); 
+0

esto parece funcionar incluso en presencia de llamadas '_.bindAll (this)', lo que hace que la propiedad '__super__' del constructor esté indefinida. – sweaver2112

+1

mejor que usar '__super__' tiene los guiones bajos sugiere un miembro privado –

4

esto parece ser casi un duplicado del Super in Backbone, por lo que desea algo como esto:

Backbone.Model.prototype.initialize.call(this); 
2

similares a @wheresrhys, pero me gustaría utilizar en lugar de aplicar la llamada en caso de BaseModel.initialize espera argumentos. Intento evitar procesar el mapa de atributos que se puede pasar a un Backbone Model en la inicialización, pero si el BaseModel fuera en realidad una Vista o una Colección, entonces podría querer establecer opciones.

var MyModel = BaseModel.extend({ 
    initialize: function() { 
     this.constructor.__super__.initialize.apply(this, arguments); 
     // Continue doing specific stuff for this child-class. 
    }, 
}); 
+0

FWIW Jeremy Ashkenas [** states **] (https://github.com/jashkenas/backbone/pull/787#issuecomment-3143358) that' __super__' no está destinado a ser utilizado directamente. – MikeSchinkel

0

aquí es un método de generación multi callSuper, sólo tiene que añadir a su clase que se extiende.

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; 
} 
Cuestiones relacionadas