I have a large json server response which nests models in models. I have no way of making the server rest based. I need to parse the json tree into collections and collections within collections. I would then like to export the backbone models in the same json structure to the server after modification.
i have a collection called sections, and using this method to nest the questions collection within each section model:
http://documentcloud.github.com/backbone/#FAQ-nested
the top level of the json response is the array of sections so i have been able to pass that directly to the sections collection, I have then used the initialize method to parse out the child questions and then deleted them from the attributes. But this means i dont get the model.questions returned in any toJSON on the sections collection.
SCC.Models.Section = Backbone.Model.extend({
initialize: function() {
var questions = this.get('questions');
this.questions = new SCC.Collections.Questions(questions);
delete this.attributes.questions;
}
});
SCC.Collections.Sections = Backbone.Collection.extend({
model: SCC.Models.Section
});
SCC.Sections = new SCC.Collections.Sections();
//imagine window.SectionData is the server response
SCC.Sections.reset(window.SectionData);
Hopefully I am clear. Let me if you need more info.
thanks.
If you have a limited number of nested models which are under you control and are not subject to frequent change, the easy way is to override
toJSON()method for your models that have nested collections:However, if you have a lot of nested collections which are subject to change, more abstract way would be nice.
I can think for example of storing all nested collections in model’s special property (say
nestedCollections) and then monkey patchingBackbone.Model.prototype.toJSONso that it will always parse all nestedCollections and add them to JSON object before returning it.Another way would be to use Backbone relational instead of nested models (it automatically handles toJSON so you won’t have to think about it).