When fetching a collection, my api response has 10 objects, but the resulting Backbone collection only has 1 model with an attributes array containing the 10 response objects....to put it another way, the fetch is not creating models out of the objects in my response...and I don't know why.
Model definition:
MyApp.Item = Backbone.Model.extend({
initialize: function(){
}
});
Collection definition:
MyApp.ItemCollection = Backbone.Collection.extend({
model: MyApp.Item,
url: '/api/v1/item/',
parse : function(response){
//api returns objects in the content attribute of response, need to override parse
return response.content;
}
});
Calling fetch:
var myCollection = new MyApp.ItemCollection();
myCollection.fetch({
traditional: true,
data: { //url params for api call
u_id: currentUser.id,
order: 'sort_date:desc',
start: 0,
num_items: 10,
format:'json'}
});
Results:
console.log(response.content);
4571221007823F95BAAFB2BDF81111XX: Object
0124207763051005AAF59694458EBFXX: Object
3324207755431003B589CEF237DBE1XX: Object
3470000061641005BFB5D9983156E0XX: Object
3515553061641005A02884677F5624XX: Object
3526033426761006AFEA9852B0DDB5XX: Object
21431252714010079E4D8413429DB0XX: Object
26570547220410068F60D1B07D2E08XX: Object
37557124663710079DDC81EE855981XX: Object
0152243312031007957B94F5073B69XX: Object
//api successfully returns an array of objects, with GUID as key
console.log(myCollection);
r {length: 1, models: Array[1], _byId: Object}
//why only one model? why not 10?
console.log(myCollection.models[0].attributes);
4571221007823F95BAAFB2BDF81111XX: Object
0124207763051005AAF59694458EBFXX: Object
3324207755431003B589CEF237DBE1XX: Object
3470000061641005BFB5D9983156E0XX: Object
3515553061641005A02884677F5624XX: Object
3526033426761006AFEA9852B0DDB5XX: Object
21431252714010079E4D8413429DB0XX: Object
26570547220410068F60D1B07D2E08XX: Object
37557124663710079DDC81EE855981XX: Object
0152243312031007957B94F5073B69XX: Object
__proto__: Object
//there they are...but why?
How can I change the fetch to get these objects added as individual models in myCollection?
The response must be an array. Each item in the array is turned into a model. Your response is an object.
Update your parse method to pull out the values (as an array) from the response into an array and it'll work.