Ich muss die initialize
-Methode der übergeordneten Klasse aus der geerbten MyModel
- Klasse heraus aufrufen, anstatt sie wie heute völlig zu überschreiben.
Wie kann ich das machen?
So sieht mein Code jetzt aus:
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.
},
});
MyModel = BaseModel.extend({
initialize: function() {
MyModel.__super__.initialize.apply(this, arguments);
// Continue doing specific stuff for this child-class.
},
});
Versuchen
MyModel = BaseModel.extend({
initialize: function() {
BaseModel.prototype.initialize.apply(this, arguments);
// Continue doing specific stuff for this child-class.
},
});
Dies funktionierte für mich, als ich versuchte, unter meinen Modellen zu erben:
MyModel.prototype.initialize.call(this, options);
Referenziert von http://documentcloud.github.com/backbone/#Model-extend
Vielen Dank.
Ich denke es wäre so
MyModel = BaseModel.extend({
initialize: function() {
this.constructor.__super__.initialize.call(this);
// Continue doing specific stuff for this child-class.
},
});
dies scheint fast ein Duplikat von Super in Backbone zu sein, also möchten Sie so etwas wie:
Backbone.Model.prototype.initialize.call(this);
Ähnlich wie @wheresrhys, aber ich würde Apply anstelle von call verwenden, falls BaseModel.initialize Argumente erwartet. Ich versuche zu vermeiden, dass die Attributzuordnung verarbeitet wird, die bei der Initialisierung an ein Backbone-Modell übergeben werden kann. Wenn das Basismodell tatsächlich eine Ansicht oder eine Sammlung wäre, möchte ich vielleicht Optionen festlegen.
var MyModel = BaseModel.extend({
initialize: function() {
this.constructor.__super__.initialize.apply(this, arguments);
// Continue doing specific stuff for this child-class.
},
});
hier ist eine CallSuper-Methode für mehrere Generationen. Fügen Sie diese einfach Ihrer Erweiterungsklasse hinzu.
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;
}