我对 backbone 还很陌生,我正在尝试构建一个简单的应用程序。这是我目前所拥有的
var Election = Backbone.Model.extend();
var Elections = Backbone.Collection.extend({
model: Election,
url: '/assets/data.json',
initialize: function() {
console.log('init col');
this.render();
return this;
},
render: function() {
console.log('rendering the collection');
return this;
},
// return this
});
var router = Backbone.Router.extend({
routes: {
'': 'root'
},
root: function(){
var collection = new Elections();
collection.fetch();
console.log(collection.length); //returns 0
}
});
var r = new router();
Backbone.history.start();
日志是这样的
> init col
> rendering the collection
> 0
但是当我在控制台中手动创建一个新集合时,它显示了正确的长度和所有内容,我假设由于某种原因路由器调用发生得太早,但不确定。这是 data.json
[
{
"year": 1868,
...
},
{
"year": 1872,
...
},
最佳答案
fetch
执行异步 HTTP (Ajax) 请求,因此您应该传递 fetch
成功回调:
collection.fetch({
success: function(){
console.log(collection.length);
}
});
关于javascript - 主干返回长度为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15013272/