![](/img/trans.png)
[英]how can i print the row line in BackboneJS *marionette* collectionView?
[英]Backbonejs - How can I print the results of a fetch?
嗨,我是Backbone的新手,我只是在玩它一点,这是我的代码:
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)
但是它不起作用。
谢谢。
有三种方法可以访问Backbone.Collection
的模型。 首先,您可以使用.get
方法根据其唯一ID查找模型。 基本上,它将查看集合中的所有模型,并将其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
最后,您可以访问Collection包装的原始模型数组。 您可以通过.models
属性(仅是一个数组)来访问它。 这不是推荐的方法。
var user = collection.models[0];
拥有用户后,您可以通过模型上的.get
方法访问该用户的任何属性:
var age = user.get("age");
user.set("age", 100);
不要忘记传递给collection.fetch
success
回调的arguments
是(collection, response, options)
。 在此处检查文档。 您可以使用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'));
}
});
小提琴供您参考。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.