user1406062
user1406062

Reputation: 883

backbone collection fetch() returns one record only

I am trying to fetch list of objects from server, the collection accepts the first record and ignores the rest.

the response from the server is of type application/json

 [{"id":1,"name":"A"}, 
  {"id":2,"name":"B"}, 
  {"id":3,"name":"C"}]

in client side,

 var collection = new Backbone.Collection;
 collection.url = 'url_to_the_resource';

 collection.fetch();
 console.log( collection.toJSON());

the output is

 [{"id":1,"name":"A"}]

edit

I call log when the collection is ready, i.e. after the asynchronous call is complete as follows:

collection.fetch().done( function() {
  console.log( collection.toJSON() );
});

and still getting one record. I have also checked backbone.js source code, and found the following at line 682

    // If a duplicate is found, prevent it from being added and
    // optionally merge it into the existing model.
    if (existing = this.get(model)) {

and added a logging right after that line, and found that backbone merges all models, why?

Upvotes: 2

Views: 1554

Answers (3)

kenberkeley
kenberkeley

Reputation: 9866

Most likely is the Override issue,
even each record of the original JSON data is totally different at all.


Revoke idAttribute property in Model or revoke modelId method in Collection may help.


You could use .findWhere({_id: pkId}) instead of .get(pkId)

Upvotes: 0

user1406062
user1406062

Reputation: 883

I found the reason,

it was because I have attached an event on the model prototype

Backbone.Model.prototype.on('request',function(model, xhr, options){ ... });

Upvotes: 1

Vitalii Petrychuk
Vitalii Petrychuk

Reputation: 14255

I can only guess. If you can provide collection code it would be great.

  1. Be sure model idAttribute (if it is overridden) is unique.
  2. Check your collection parse method if it is overridden. It should return the array of objects.
  3. Try to play with add, remove, merge http://backbonejs.org/#Collection-set.

Upvotes: 2

Related Questions