Skip to content

Instantly share code, notes, and snippets.

@danroberts
Forked from borestad/backbone.$super.js
Created October 11, 2012 20:53
Show Gist options
  • Save danroberts/3875410 to your computer and use it in GitHub Desktop.
Save danroberts/3875410 to your computer and use it in GitHub Desktop.
super call within Backbone.js - adding multiple levels of inheritance.
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;
var $super = function($that, funcName){
funcName = funcName || 'initialize';
// _.bindAll messes upp constructor
// Will now handle multiple inheritance, and extend the events and defaults.
_.extend({}, $that.attributes, this.constructor.__super__.defaults);
_.extend({}, $that.events, this.constructor.__super__.events)
var _super = this.constructor.__super__ || this.__proto__.constructor.__super__;
return _super[funcName].apply($that, _.rest(arguments));
},
_$super = function($that, 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;
usage:
var Parent = Backbone.model.extend({
})
var Child = Parent.extend({
initialize:function(attributes) {
Child.prototype.$super(this);
}
})
var SubChild = Child.extend({
initialize:function(attributes) {
SubChild.prototype.$super(this);
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment