Ari
Ari

Reputation: 4191

Iterating Backbone Collection

I've setup a backbone collection for Users and when I execute the fetch method, I get back a JSON object along the lines of: {"users": [{...}, {...}, ...], size: number} from the server. Confusingly, when I execute the code below, instead of getting each user object, I get a single "child" object, which has two attributes: users and size; can anyone help me understand why? Thanks.

display: function(){
  this.collection.each(function(user){ 
    console.log("main", user); 
  });
}

Upvotes: 6

Views: 8388

Answers (2)

Justin Thomas
Justin Thomas

Reputation: 5848

Add a method on the collection called parse:

var collection = new Backbone.Collection({
   parse: function(response) {
       return response.users;
   }
});

Upvotes: 7

Matt Ball
Matt Ball

Reputation: 359776

This makes perfect sense to me. Look at the JSON: it has two properties: users and size.

You probably just want to iterate over collection.users:

display: function(){
  this.collection.users.each(function(user){ 
    console.log("main", user); 
  });
}

Alternately, just assigned collection to foo.users instead of foo (where foo is the object created by parsing the returned JSON).

Upvotes: 4

Related Questions