Skip to content

Instantly share code, notes, and snippets.

@timrchavez
Created March 10, 2012 23:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timrchavez/2014084 to your computer and use it in GitHub Desktop.
Save timrchavez/2014084 to your computer and use it in GitHub Desktop.
Make backbone.js inhertance work for you! (or make view inheritance work in general)
/**
* Give backbone an easier way to access super properties and methods.
*/
Backbone.View.prototype.parent = Backbone.Model.prototype.parent = Backbone.Collection.prototype.parent = function(attribute, options) {
/**
* Call this inside of the child initialize method. If it's a view, it will extend events also.
* this.parent('inherit', this.options); <- A views params get set to this.options
*/
if(attribute == "inherit") {
this.parent('initialize', options); // passes this.options to the parent initialize method
//extends child events with parent events
if(this.events) { $.extend(this.events, this.parent('events')); this.delegateEvents(); }
return;
}
/**
* Call other parent methods and attributes anywhere else.
* this.parent('parentMethodOrOverriddenMethod', params) <- called anywhere or inside overridden method
* this.parent'parentOrOverriddenAttribute') <- call anywhere
*/
return (_.isFunction(this.constructor.__super__[attribute])) ?
this.constructor.__super__[attribute].apply(this, _.rest(arguments)) :
this.constructor.__super__[attribute];
};
var ParentView = Backbone.View.extend({
'anAttribute': "YO!",
'events': {
'click .parentSomething': "handleParentSomethingClick"
},
'handleParentSomethingClick': function() {
console.log('parent something was clicked.');
},
'parentOnlyFunction': function(arg) {
console.log('a function only in the parent view with arg:', arg);
}
});
var ChildView = ParentView.extend({
'initialize': function() {
//inherits events and calls the parent initialize with options
this.parent('inherit', this.options);
//calls parentOnlyFunction and outputs "Hello Parent Only Function" at the end of the console log
this.parent('parentOnlyFunction', "Hello Parent Only Function!");
//logs "YO!"
console.log(this.parent('anAttribute'));
},
'events': {
'click .something': "handleSomethingClick"
},
'handleSomethingClick': function() {
console.log('something was clicked.');
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment