Backbone.js 主干:从集合中获取模型

Backbone.js 主干:从集合中获取模型,backbone.js,Backbone.js,我在玩脊梁骨游戏,正在经历一些我不太理解的事情: 1) 我在“data/applications.js”中创建了一些模拟数据 2) 我正在尝试检索集合中的单个“应用程序” ApplicationModel = Backbone.Model.extend({}); ApplicationCollection = Backbone.Collection.extend({ url: "data/applications.json", model: ApplicationModel });

我在玩脊梁骨游戏,正在经历一些我不太理解的事情:

1) 我在“data/applications.js”中创建了一些模拟数据

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

我感觉我遗漏了什么?

当您使用主干获取数据时,它是异步完成的,这意味着您的脚本在获取时将继续执行。要检索应用程序,您必须等待获取结束,如下所示:

applications.fetch({success: function() {
        console.log(applications.get(applicationId));
}});
applications.fetch({success: function() {
        console.log(applications.get(applicationId));
}});