我正在尝试了解 Backbone 并尝试创建一些小的 REST API 前端,但无法开始View
工作。
fetch()
返回三个元素的有效 JSON 数组。并且this.collection.models
不是空的(typeof object
- []
) - 它有树子对象元素。但是each
迭代不会触发。
当检查 collection.models 是否存在时console.log(this.collection.models);
,看起来一切正常:
如果有任何建议,我将不胜感激!
var Account = Backbone.Model.extend({});
var AccountsCollection = Backbone.Collection.extend({
model: Account,
url: 'api/v1/accounts',
initialize: function () {
this.fetch();
}
});
var AccountsView = Backbone.View.extend({
render: function() {
// Check if there is something
console.log(this.collection.models);
// This doesn't work
_.each(this.collection.models, function(model) {
console.log(model);
});
// Neither this
this.collection.each(function(model) {
console.log(model);
});
}
});
var a = new AccountsView({collection: new AccountsCollection()});
a.render();