Skip to content

Instantly share code, notes, and snippets.

@serkanyersen
Created September 29, 2013 21:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save serkanyersen/6756958 to your computer and use it in GitHub Desktop.
Save serkanyersen/6756958 to your computer and use it in GitHub Desktop.
Allows you to correctly extend existing models and views while utilizing the properties on the base object, also adds super class support
var Car = Backbone.Model.extend({
defaults:{
engine: 'gasoline',
hp: 0,
doors: 4,
color: 'generic'
},
engine: function(){
return 'Wroomm';
}
});
// Ferrari will have all attributes from Car Model
// But will also have it's own modifications
var Ferrari = Car.fullExtend({
defaults: {
hp: 500,
color: 'red',
doors: 2
},
// Engine method can use the engine method on Car too
engine: function(){
var ret = this._super.engine();
return ret + '!!!!';
}
});
(function(Model){
'use strict';
// Additional extension layer for Models
Model.fullExtend = function(protoProps, staticProps){
// Call default extend method
var extended = Model.extend.call(this, protoProps, staticProps);
// Add a usable super method for better inheritance
extended._super = this.prototype;
// Apply new or different defaults on top of the original
if(protoProps.defaults){
for(var k in this.prototype.defaults){
if(!extended.prototype.defaults[k]){
extended.prototype.defaults[k] = this.prototype.defaults[k];
}
}
}
return extended;
};
})(Backbone.Model);
(function(View){
'use strict';
// Additional extension layer for Views
View.fullExtend = function(protoProps, staticProps){
// Call default extend method
var extended = View.extend.call(this, protoProps, staticProps);
// Add a usable super method for better inheritance
extended._super = this.prototype;
// Apply new or different events on top of the original
if(protoProps.events){
for(var k in this.prototype.events){
if(!extended.prototype.events[k]){
extended.prototype.events[k] = this.prototype.events[k];
}
}
}
return extended;
};
})(Backbone.View);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment