I have multiple backbone models with nested sub-models. Here's how I've approached the solution:
Models.Base = Backbone.Model.extend ({
relatedModels: {},
/**
* Parses data based on the list of related models.
*
* @since Version 1
* @param {Object} response Response
* @return {Object} Parsed data
*/
parse: function (response) {
var key,
embeddedClass,
embeddedData;
for (key in this.relatedModels) {
embeddedClass = this.relatedModels[key];
embeddedData = response[key];
response[key] = new embeddedClass (embeddedData, { parse: true });
}
return response;
}
});
(utilizing information from this post - Nested Models in Backbone.js, how to approach)
Everything works smoothly when fetching data from the server:
Models.Individual = Models.Base.extend({
idAttribute: "idInd",
urlRoot: "data/individuals/save",
relatedModels: {
details: Collections.DetailList,
relationships: Collections.RelationshipList
}
});
...However, when I try to initialize a model using plain JSON, like this:
var Ind = new Models.Individual ({
idInd: 1,
name: "Bob Holness",
details: [
{ option: "I'd like an 'e' please, bob" },
{ option: "Can I have a 'p' please, bob" }
],
relationships: []
});
...it doesn't seem to parse "details". It appears that the Parse function is not being executed. How can I ensure that the data is parsed in both scenarios?