Skip to content

Instantly share code, notes, and snippets.

@tspringborg
Created October 7, 2013 09:24
Show Gist options
  • Save tspringborg/6865033 to your computer and use it in GitHub Desktop.
Save tspringborg/6865033 to your computer and use it in GitHub Desktop.
backbonejs inheritance
///facilitates inheritance ....gist from https://gist.github.com/1542120
;(function(Backbone) {
// The super method takes two parameters: a method name
// and an array of arguments to pass to the overridden method.
// This is to optimize for the common case of passing 'arguments'.
function _super(methodName, args) {
// Keep track of how far up the prototype chain we have traversed,
// in order to handle nested calls to _super.
this._superCallObjects || (this._superCallObjects = {});
var currentObject = this._superCallObjects[methodName] || this, parentObject = findSuper(methodName, currentObject);
this._superCallObjects[methodName] = parentObject;
var result = parentObject[methodName].apply(this, args || []);
delete this._superCallObjects[methodName];
return result;
}
// Find the next object up the prototype chain that has a
// different implementation of the method.
function findSuper(methodName, childObject) {
var object = childObject;
while(object[methodName] === childObject[methodName]) {
object = object.constructor.__super__;
}
return object;
}
_.each(["Model", "Collection", "View", "Router"], function(klass) {
Backbone[klass].prototype._super = _super;
});
})(Backbone);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment