2014-01-14 44 views
2

您好我是新来的骨干,我只是用了一点玩了,这里是我的代码:Backbonejs - 如何打印提取结果?

var Users = Backbone.Collection.extend ({ 
     url : 'http://backbonejs-beginner.herokuapp.com/users' 
    }); 

    var users = new Users(); 
    users.fetch({ 
     success: function() { 
      console.log(users); 
     } 
    }); 

取指令调用成功,我有一个对象,它看起来像返回:

[ 
    { 
    "id": "hqel839m1071rbggsxf7", 
    "firstname": "Thomas", 
    "lastname": "Davis", 
    "age": 12 
    } 
] 

如何打印结果的不同部分? 例如,我想打印第一个项目的“id”参数。我可以像数组一样迭代它吗?我试过console.log(users[0].id)但它不起作用。

谢谢。

回答

3

有三种不同的方法可以访问Backbone.Collection中的模型。首先,您可以使用.get方法根据其唯一标识查找模型。这基本上会查看集合中的所有模型,并将它们的id属性与提供的属性进行比较。

var user = collection.get('unique_id'); // return an instance, or null 

第二种方法是使用.at方法按索引获取模型。如果您的模型已排序,这非常有用。如果它们没有排序,他们将通过插入要取回(即,它们被提供到集合中的顺序排列):

var user = collection.at(0); // return the first model in the collection 

最后,您可以访问模型的原始阵列集合包装。您可以通过.models属性访问此属性,该属性只是一个数组。这不是推荐的方法。

var user = collection.models[0]; 

一旦你有一个用户,你可以通过.get方法来访问你的模型的用户的任何属性:

var age = user.get("age"); 
user.set("age", 100); 

您可以查看文档模型get方法here,和文件为Backbone.Collectionhere

+0

当我尝试执行console.log(users [0] .get(“id”));我得到“Uncaught TypeError:Can not call method'get'of undefined” – zeion

+0

对不起,我编辑了我的答案,我忘记了模型数组。我所链接的内容现在可以工作。 –

3

不要忘记arguments传递给success回调collection.fetch这是(collection, response, options)。检查文档here。您可以使用collection参数来选择特定的model。请查看以下代码:

var Users = Backbone.Collection.extend ({ 
    url : 'http://backbonejs-beginner.herokuapp.com/users' 
}); 

var users = new Users(); 
users.fetch({ 
    success: function (collection, response, options) { 
     //Will log JSON objects of all User objects 
     console.log(collection.toJSON()); 
     //You can get a Model using 'id' 
     var user = collection.get("hqesig1ea1br2k6horay"); 
     // Will log User Model for id "hqesig1ea1br2k6horay" 
     console.log(user); 
     //You can then fetch Model attributes this way 
     console.log("ID: ", user.get('id')); 
     console.log("First name: ", user.get('firstname')); 
     console.log("Lastname : ", user.get('lastname')); 
    } 
}); 

A fiddle供您参考。