BackboneJS
From Organic Design wiki
Extending model classes
This example sub-classes an existing model and ensures that new instances have their type property set.
var subModel = mainModel.extend({
constructor: function( attributes, options ) {
attributes.type = 'subModel';
Backbone.Model.apply( this, arguments );
},
});
Collections of various sub-classes
Normally a collection's members are all of the same class, but you may want the members to be of various sub-classes as well. You can replace the object on the add event as follows.
myCollection.on( 'add', upgradeObject, lg );
function upgradeObject( obj ) {
var upg = createObject( obj.attributes );
for( var i in upg ) obj[i] = upg[i];
}
function createObject( atts ) {
var cls = ... // figure out the sub-class you want from the atts
var obj = new lg[cls](atts);
for( var i in atts ) obj[i] = atts[i];
obj.id = atts.id;
return obj;
};