Created
September 29, 2013 21:57
-
-
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
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
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 + '!!!!'; | |
} | |
}); |
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
(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