Skip to content

Instantly share code, notes, and snippets.

@vote539
Created July 8, 2013 09:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vote539/5947313 to your computer and use it in GitHub Desktop.
Save vote539/5947313 to your computer and use it in GitHub Desktop.
My implementation of nested models for Backbone.js. Read more at http://codrspace.com/vote539/nested-models-and-collections-in-backbone-js/
Backbone.Model.prototype.forward = function (attribute, subModel, options) {
var self = this; // parent model
var property = (options && options.property) ?
options.property : attribute;
self[property] = subModel; // save the subModel in the specified property
subModel.set(self.get(attribute)); // add any existing data to the subModel
self.on("change:" + attribute, function(model, value, options){
subModel.set(value, options);
});
// Implement here all methods on the child that you need to trigger change
// events up in the rest of the model tree.
//
// For example, here is how you could implement the "add" function for
// Backbone.Collection.
subModel.add = function (model, options) {
var collection = _.clone(self.get(attribute));
collection.push(model.attributes);
self.set(attribute, collection);
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment