BrainLikeADullPencil
BrainLikeADullPencil

Reputation: 11663

collection.reset not populating with all the models

My Backbone collection calls a fetch like this

collection.fetch({data : {product_type: foo, year: bar}, processData: true, success: function(response){
            console.log(response, "response from server");
            collection.reset(response);
        }});

In the Chrome console, it shows that the array has six records, but when I inspect the response further, there are actually 0 models in the array. You can see this below by noticing the number 6 in the first line and Array[0] in the last line:

MyCollection {length: 6, models: Array[6], _byId: Object, sortField: "date", sortDirection: "DESC"…}
_byId: Object
_events: Object
_listenId: "l1"
length: 0
model: function (attrs, options) {
models: Array[0]  
//...other details  ommitted...// 

Furthermore, only 1 of my 6 expected models appears in the view. Given the above, I thought maybe either 0 or 6 would appear, but there is 1.

Why isn't the collection resetting with all 6 of the models?

Upvotes: 0

Views: 26

Answers (1)

Eugene Glova
Eugene Glova

Reputation: 1553

Based on docs Collection#fetch I can see that the success callback has 3 arguments

(collection, response, options)

So in your case response is a collection updated based on JSON array from the server, so you don't need to reset it again, instead you reset it with collection means you add clear the collection and add new model which is actually a collection itself. So you may use instead

collection.reset(response.models)

but I think you should not perform any action on collection within success callback, backbone does it for you automatically.

Upvotes: 1

Related Questions