我正在玩Backbone,正在经历一些我不太了解的事情:
1)我在“data / applications.js”中创建了一些模拟数据
[
{
"id": "1",
"title": "Title #1",
"image": "some/path1"
},
{
"id": "2",
"title": "Title #2",
"image": "some/path2"
},
{
"id": "3",
"title": "Title #3",
"image": "some/path4"
},
{
"id": "4",
"title": "Title #4",
"image": "some/path4"
}
]
2)我试图在集合中检索单个“应用程序”
ApplicationModel = Backbone.Model.extend({});
ApplicationCollection = Backbone.Collection.extend({
url: "data/applications.json",
model: ApplicationModel
});
var applications = new ApplicationCollection();
applications.fetch();
var application = applications.get(applicationId); // I get this from route
console.log(applicationId); // returns 2
console.log(applications); // returns the collection with 4 models
console.log(application); // returns undefined
我有一种感觉我错过了什么?
答案 0 :(得分:1)
当您使用Backbone获取数据时,它是异步完成的,这意味着您的脚本在获取时继续执行。要检索您的应用程序,您必须等待提取结束:
applications.fetch({success: function() {
console.log(applications.get(applicationId));
}});