![](/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.