BackboneJS

From Organic Design wiki
Cone.png This article or section is a stub. Stubs are articles that have not yet received substantial attention from the authors. They are short or insufficient pieces of information and require additions to further increase the article's usefulness. The project values stubs as useful first steps toward complete articles.


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;
};

See also