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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With