在Backbone中访问父类
我需要从inheritance的MyModel
类中调用父类的initialize
方法,而不是像我今天所做的那样完全覆盖它。
我怎么能这样做?
以下是我的代码现在看起来:
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. }, });
尝试
MyModel = BaseModel.extend({ initialize: function() { BaseModel.prototype.initialize.apply(this, arguments); // Continue doing specific stuff for this child-class. }, });
这对我来说,当我试图inheritance我的模型:
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. }, });
这似乎几乎是在骨干超级副本,所以你想这样的事情:
Backbone.Model.prototype.initialize.call(this);
与@wheresrhys类似,但是我会在BaseModel.initialize需要参数的情况下使用apply而不是调用。 我尝试避免处理可以在初始化时传递给Backbone模型的属性映射,但是如果BaseModel实际上是一个View或一个集合,那么我可能要设置选项。
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; }
你可能会考虑用functioninheritance来重写你的代码。
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 }; };