Created
July 8, 2013 09:00
-
-
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/
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
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