Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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); 
  });
}
like image 679
Ari Avatar asked Dec 01 '11 21:12

Ari


2 Answers

Add a method on the collection called parse:

var collection = new Backbone.Collection({
   parse: function(response) {
       return response.users;
   }
});
like image 84
Justin Thomas Avatar answered Oct 19 '22 23:10

Justin Thomas


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).

like image 31
Matt Ball Avatar answered Oct 20 '22 00:10

Matt Ball