我有一个视图,它正在对集合进行fetch()并从服务器返回一些模型。
ProductsView = Backbone.View.extend({
initialize: function() {
_.bindAll(this, 'render');
this.collection = new ProductCollection();
this.collection.fetch({data: {limit : this.options.limit}});
console.log(this.collection);
this.render();
},
render: function() {
var template = _.template( $("#product-template").html(), this );
$(this.el).html( template );
return this;
}
});
在上面的console.log中,我看到如下对象:
products.view.js:13
d
_byCid: Object
_byId: Object
length: 7
models: Array[7]
__proto__: x
models
就在那里,但当我console.log(this.collection.models)
时它只显示[]
,在模型中,是一个像这样的对象数组:
models: Array[7]
0: d
1: d
2: d
3: d
4: d
5: d
6: d
其中每个都有attributes
,其中包含已返回的值。
我在使用this.collection.models
或使用get()
时无法显示模型的原因也不起作用。
非常感谢!
答案 0 :(得分:6)
通常this.collection.fetch({data: {limit : this.options.limit}})
是异步操作,因此下一行不一定要打印collection
的正确内容。
相反,您应该使用success
方法提供的error
和fetch
回调作为其options
参数的一部分(或收听集合的change
事件),像这样:
this.collection.fetch(
{
data: { limit : this.options.limit },
success : function(collection, rawresponse) {
// do something with the data, like calling render
}
}
);
为了完整起见:
this.collection.on('change', function(){ // some handling of the data };
this.collection.fetch();
是基于事件的方法。