I have 2 models and one collection. JobSummary
is a model, JobSummaryList
is a collection of JobSummary
items, and then I have a
Your parse()
function shouldn't set()
anything, its a better practice to just return the attributes, Backbone will take care of setting it. e.g.
parse: function(response) {
response.summaryList = new JobSummaryList(response.summaryList);
return response;
}
Whatever you return from parse()
is passed to set().
Not returning anything (which is like returning undefined
) is the same as calling set(undefined)
, which could cause it not to pass validation, or some other unexpected results if your custom validate()
/set()
methods expects to get an object. If your validation or set()
method fails because of that, the options.success
callback passed to Backbone.Model#fetch()
won't be called.
Also, to make this more generic, so that set()
ing to a plain object from other places (and not only from the server response) also effects it, you might want to override set()
instead:
set: function(attributes, options) {
if (attributes.summaryList !== undefined && !(attributes.summaryList instanceof JobSummaryList)) {
attributes.summaryList = new JobSummaryList(attributes.summaryList);
}
return Backbone.Model.prototype.set.call(this, attributes, options);
}
You might also find Backbone-relational interesting - it makes it much easier to deal with collections/models nested inside models.
edit I forgot to return from the set() method, the code is now updated