Skip to content

Instantly share code, notes, and snippets.

@ckniffen
Created October 8, 2013 20:55
Show Gist options
  • Save ckniffen/6891507 to your computer and use it in GitHub Desktop.
Save ckniffen/6891507 to your computer and use it in GitHub Desktop.
Tweak of Backbone.extend to allow deeper inheritance for properties such as `defaults` and `options` and another property you also want extended.
/* global _, Backbone */
(function(_, Backbone){
// Helper function to correctly set up the prototype chain, for subclasses.
// Similar to `goog.inherits`, but uses a hash of prototype properties and
// class properties to be extended.
Backbone.deepInheritableProperties = ['options', 'defaults'];
var inherits = function(protoProps, staticProps) {
var parent = this;
var child;
// The constructor function for the new subclass is either defined by you
// (the "constructor" property in your `extend` definition), or defaulted
// by us to simply call the parent's constructor.
if (protoProps && _.has(protoProps, 'constructor')) {
child = protoProps.constructor;
} else {
child = function(){ return parent.apply(this, arguments); };
}
// Add static properties to the constructor function, if supplied.
_.extend(child, parent, staticProps);
// Set the prototype chain to inherit from `parent`, without calling
// `parent`'s constructor function.
var Surrogate = function(){ this.constructor = child; };
Surrogate.prototype = parent.prototype;
child.prototype = new Surrogate();
// Add prototype properties (instance properties) to the subclass,
// if supplied.
_.each(Backbone.deepInheritableProperties, function(key){
protoProps[key] = _.defaults({}, child.prototype[key], protoProps[key]);
});
if (protoProps){ _.extend(child.prototype, protoProps); }
// Set a convenience property in case the parent's prototype is needed
// later.
child.__super__ = parent.prototype;
return child;
};
// Set up inheritance for the model, collection, router, view and history.
Backbone.Model.inherits = Backbone.Collection.inherits = Backbone.Router.inherits = Backbone.View.inherits = Backbone.History.inherits = inherits;
})(_, Backbone);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment