Two models and a collection are in play. The first model, JobSummary
, is accompanied by the second model, JobSummaryList
, which serves as a collection of JobSummary
items. Additionally, there exists a model called JobSummarySnapshot
that houses a JobSummaryList
:
JobSummary = Backbone.Model.extend({});
JobSummaryList = Backbone.Collection.extend({
model: JobSummary
});
JobSummarySnapshot = Backbone.Model.extend({
url: '/JobSummaryList',
defaults: {
pageNumber: 1,
summaryList: new JobSummaryList()
}
});
Upon calling fetch
on the JobSummarySnapshot
object, everything is retrieved successfully... with one exception. Moving through the summaryList
collection reveals that all entries are labeled as type object
rather than JobSummary
.
The reason behind this behavior seems logical, considering that aside from the defaults
object declaration, no indication is given to recognize that the summaryList
should consist of JobSummaryList
elements. While manual conversion to JobSummary
objects is an option, it would be preferable to achieve this automatically.
A test setup is provided (functional jsfiddle here):
// Test Data
var returnData = {
pageNumber: 3,
summaryList: [
{
id: 5,
name: 'name1'
},
{
id: 6,
name: 'name2'
}
]
};
// Fake Server Configuration
var fakeserver = sinon.fakeServer.create();
fakeserver.respondWith('GET', '/JobSummaryList', [200,
{
'Content-Type': 'application/json'},
JSON.stringify(returnData)]);
var callback = sinon.spy();
// Fetching Snapshot Data
var summarySnapshot = new JobSummarySnapshot();
summarySnapshot.bind('change', callback);
summarySnapshot.fetch();
fakeserver.respond();
var theReturnedList = callback.getCall(0).args[0].attributes.summaryList;
_.each(theReturnedList, function(item) {
console.log('Original Item: ');
console.log(item instanceof JobSummary); // IS FALSE
var convertedItem = new JobSummary(item);
console.log('converted item: ');
console.log(convertedItem instanceof JobSummary); // IS TRUE
});
An update follows below:
JobSummarySnapshot = Backbone.Model.extend({
url: '/JobSummaryList',
defaults: {
pageNumber: 1,
summaryList: new JobSummaryList()
},
parse: function(response) {
this.set({pageNumber: response.pageNumber});
var summaryList = new JobSummaryList();
summaryList.add(response.summaryList);
this.set({summaryList: summaryList});
}
});
Implementing this solution has shown promise. The inquiry remains open for any additional insights or feedback.