Ответ 1
MyModel = BaseModel.extend({
initialize: function() {
MyModel.__super__.initialize.apply(this, arguments);
// Continue doing specific stuff for this child-class.
},
});
Мне нужно вызвать метод initialize
родительского класса изнутри наследуемого MyModel
-класса, а не полностью переписать его, как я делаю сегодня.
Как я могу это сделать?
Здесь мой код выглядит прямо сейчас:
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.
},
});
Try
MyModel = BaseModel.extend({
initialize: function() {
BaseModel.prototype.initialize.apply(this, arguments);
// Continue doing specific stuff for this child-class.
},
});
Это сработало для меня, когда я пытался наследовать среди своих моделей:
MyModel.prototype.initialize.call(this, options);
Ссылка на http://documentcloud.github.com/backbone/#Model-extend
Спасибо.
Я думаю, что это будет
MyModel = BaseModel.extend({
initialize: function() {
this.constructor.__super__.initialize.call(this);
// Continue doing specific stuff for this child-class.
},
});
похоже, это почти дубликат Super in Backbone, поэтому вы хотите что-то вроде этого:
Backbone.Model.prototype.initialize.call(this);
Подобно @wheresrhys, но я бы использовал применение вместо вызова в случае, если BaseModel.initialize ожидает аргументы. Я стараюсь не обрабатывать карту атрибутов, которая может быть передана в базовую модель при инициализации, но если BaseModel на самом деле представляет собой представление или коллекцию, тогда мне может потребоваться установить параметры.
var MyModel = BaseModel.extend({
initialize: function() {
this.constructor.__super__.initialize.apply(this, arguments);
// Continue doing specific stuff for this child-class.
},
});
здесь многопользовательский метод callSuper, просто добавьте его в расширяемый класс.
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;
}
Возможно, вы захотите переписать код с помощью функционального наследования.
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
};
};