[英]Backbone Collection View each
我是Backbone.js的新手,并且在集合视图上遇到了一些麻烦。 这是我想做的事情:
var customersCollection = new _App.Collections.Customers();
var customersView = new _App.Views.Customers({collection: customersCollection});
customersView.render();
这是一个观点-我不明白为什么我不能遍历集合:
_App.Views.Customers = Backbone.View.extend({
render: function() {
console.log('Here is my collection');
console.log(this.collection);
console.log('Now lets iterate over it...');
_.each(this.collection, function(item) {
console.log(item);
}, this);
console.log('...done');
return this;
}
});
我在chrome控制台中看到的内容:
Here is my collection
child {length: 0, models: Array[0], _byId: Object, constructor: function, url: "/admin/customers/latest.json"…}
_byId: Object
length: 5
models: Array[5]
__proto__: Surrogate
Now lets iterate over it...
...done
因此,我无法弄清楚为什么可以看到一个收藏集,但每个收藏集都看不到。 谢谢
// 解决了
我发现了为什么会这样。 完全错过了.fetch()是异步的,因此调用render()时,集合中仍然不存在数据。 该代码现在对我有效,因此我可以继续使用模板等
_App.Views.Customers = Backbone.View.extend({
initialize: function() {
this.collection = new _App.Collections.Customers();
this.collection.on('sync', this.render, this);
this.collection.fetch();
},
render: function() {
this.collection.each(function(item) {
console.log(item);
});
return this;
}
});
new _App.Views.Customers();
问候,尼古拉
您没有正确使用_.each
。
应该:
_.each(this.collection.models, function(item) {
console.log(item);
},this);
或更好:
this.collection.each(function(item) {
console.log(item);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.