Created
August 7, 2012 13:50
-
-
Save borestad/3285492 to your computer and use it in GitHub Desktop.
super call within Backbone.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var $super = function(funcName){ | |
funcName = funcName || 'initialize'; | |
// _.bindAll messes upp constructor | |
// TODO: Add more tests with multiple inheritance | |
var _super = this.constructor.__super__ || this.__proto__.constructor.__super__; | |
return _super[funcName].apply(this, _.rest(arguments)); | |
}, | |
_$super = function(funcName){ | |
funcName = funcName || 'initialize'; | |
// _.bindAll messes upp constructor | |
// TODO: Add more tests with multiple inheritance | |
var _super = this.constructor.__super__ || this.__proto__.constructor.__super__; | |
return _super[funcName]; | |
}; | |
// Create a superclass method | |
Backbone.Model.prototype.$super = | |
Backbone.Collection.prototype.$super = | |
Backbone.NestedModel.prototype.$super = | |
Backbone.View.prototype.$super = $super; | |
Backbone.Model.prototype._$super = | |
Backbone.Collection.prototype._$super = | |
Backbone.NestedModel.prototype._$super = | |
Backbone.View.prototype._$super = _$super; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey... I'm not sure if the way I did it is very clean or not... but if you check out my fork, I think I've made it work so that you can do multiple levels of inheritance...
The problem is that you need a reference to both the actual backbone model, and the prototype chain as you continue to move up the inheritance tree. If you keep it at this... than this.constructor.super will always point to one level above the SubChild, causing an infinite loop.
If you keep a reference to the actual backbone model, which I'm calling $that, you can bind the initialize context to $that, while keeping the prototype context to the proper this as you move up the change.
Let me know if this makes any sense or seems correct to you.