Created
July 17, 2012 03:41
-
-
Save faridlab/3126880 to your computer and use it in GitHub Desktop.
Make backbone.js inhertance work for you! (or make view inheritance work in general)
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
/** | |
* 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