简体   繁体   English

迭代Backbone集合

[英]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. 我为Users设置了一个骨干集合,当我执行fetch方法时,我得到了一个JSON对象: {"users": [{...}, {...}, ...], size: number}来自服务器。 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 ; 令人困惑的是,当我执行下面的代码时,我得到一个“子”对象,而不是获取每个user对象,它有两个属性用户大小 ; 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: 在名为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. 看看JSON:它有两个属性: 用户大小。

You probably just want to iterate over collection.users : 您可能只想迭代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). 或者,只是将collection分配给foo.users而不是foo (其中foo是通过解析返回的JSON创建的对象)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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