的问题是,这种代码:this.fetch()
完成之前
console.log("the length "+collections.length);
for (i=1;i<collections.length;i++)
{
console.log("done "+ collections.at(i).get("name"));
}
最终被执行。你需要要么把你的代码this.fetch
的success
回调,像这样:
var Collection = Backbone.Collection.extend({
url: '/data.json',
initialize: function() {
this.fetch({
success: function() {
console.log(collections, 'the length ' + collections.length);
for (var i = 0; i < collections.length; i++) {
console.log('done ' + collections.at(i).get('name'));
}
}
});
}
});
var collections = new Collection();
或通过听取收集的sync
事件,当this.fetch
已成功完成时出现。这种模式在Backbone应用程序中更常用。
var Collection = Backbone.Collection.extend({
url: '/data.json',
initialize: function() {
this.listenTo(this, 'sync', this.syncExample);
this.fetch();
},
syncExample: function() {
console.log(collections, 'the length ' + collections.length);
for (var i = 0; i < collections.length; i++) {
console.log('done ' + collections.at(i).get('name'));
}
}
});
var collections = new Collection();
你可以阅读更多关于骨干的事件系统和listenTo
功能here。
@EugenePodskal你说得对,当我看到这个问题时我很匆忙,并且谢谢你提醒我完成它。 – Evilsanta