简体   繁体   中英

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); 
  });
}

Add a method on the collection called parse:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM