Backbone.js的collection.models没有显示,但有 [英] Backbone.js collection.models not showing, but there
问题描述
我有在做一个取()到集合,并从服务器返回的一些模型视图。
I have a view that's doing a fetch() to a collection and returning some models from the server.
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,我看到这样的目标:
In the console.log above, I see the object like this:
products.view.js:13
d
_byCid: Object
_byId: Object
length: 7
models: Array[7]
__proto__: x
的模式
是存在的,但是当我做的console.log(this.collection.models)
这表明刚 []
,该机型里面,是这样的对象数组:
The models
is there, but when I do console.log(this.collection.models)
it shows just []
, inside the models, is an array of objects like this:
models: Array[7]
0: d
1: d
2: d
3: d
4: d
5: d
6: d
每个这些都属性
与所返回的值。
Each of these have attributes
with the values that were returned.
任何想法,为什么当我使用的车型将不会显示 this.collection.models
或使用的get()
也不行。
Any idea why the models won't show when I use this.collection.models
or using get()
doesn't work either.
非常感谢!
推荐答案
在一般 this.collection.fetch({数据:{限制:this.options.limit}})
是一个异步操作,让你下一行不一定要打印收集正确的内容
。
In general this.collection.fetch({data: {limit : this.options.limit}})
is an asynchronous operation, so you next line is not necessarily going to print the correct content of the collection
.
相反,你应该使用成功
和错误
回调取
方法提供作为参数的选项的一部分
(或收听收藏的更改
事件),像这样:
Instead you should use success
and error
callbacks the fetch
method provides as part of its options
parameter (or listen to collection's change
event), like so:
this.collection.fetch(
{
data: { limit : this.options.limit },
success : function(collection, rawresponse) {
// do something with the data, like calling render
}
}
);
有关completness缘故:
For completness sake:
this.collection.on('change', function(){ // some handling of the data };
this.collection.fetch();
是基于事件的方法。
is the event-based method.
这篇关于Backbone.js的collection.models没有显示,但有的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!