[英]backbone.js collection.get() undefined
I'm using Backbone, and I have a collection full of 7 models. 我正在使用Backbone,并且有一个完整的包含7个模型的集合。
I want to grab one model and pull it from the collection. 我想拿一个模型并将其从收藏夹中取出。 However, everything I try returns
undefined
. 但是,我尝试的所有操作都返回
undefined
。
Here is how I populate the collection 这是我填充集合的方式
var coll = new TestCollection();
coll.fetch();
A simple console log call shows that the collection is populated from the JSON file 一个简单的控制台日志调用显示该集合是从JSON文件填充的
child
_byCid: Object
_byId: Object
_onModelEvent: function () { [native code] }
_removeReference: function () { [native code] }
length: 7
models: Array[7]
__proto__: ctor
However I have tried a whole bunch of approaches in order to grab one of these models from the collection including coll.at(1)
and coll.get(1)
but each returns undefined
. 但是,我尝试了很多方法来从集合中获取其中一个模型,包括
coll.at(1)
和coll.get(1)
但是每种方法都返回undefined
。
Does anyone have any ideas? 有人有什么想法吗?
The fetch
method is an AJAX call and that means that it is asynchronous. fetch
方法是AJAX调用,这意味着它是异步的。 Your console.log
call puts a live reference into the console (so it is sort of asynchronous) so you end up with this sequence of events: 您的
console.log
调用将实时引用放入控制台中(因此它是异步的),因此您会遇到以下事件序列:
coll.fetch()
. coll.fetch()
。 $.ajax
call. $.ajax
呼叫。 console.log(coll)
and a live reference goes in the console. console.log(coll)
,然后在控制台中添加实时引用。 coll.at(1)
or coll.get(1)
and get nothing because 2 hasn't returned from the server yet. coll.at(1)
或coll.get(1)
一无所获,因为服务器尚未返回2 。 coll
has been populated by now so the coll
reference in the console includes the models that came back in 5 . coll
已经被填充,因此控制台中的coll
引用包括5中返回的模型。 A successful fetch
triggers a "reset"
event so you should be listening to that event if you want to know when the collection is populated: 成功
fetch
将触发"reset"
事件,因此,如果您想知道何时填充集合,则应该监听该事件:
coll.on('reset', this.some_method);
Or, for a one-shot notification, you could use the success
callback: 或者,对于一次通知,您可以使用
success
回调:
coll.fetch({
success: function(collection, response) {
//...
}
});
In newer versions of Backbone, you need to pass the reset: true
option to fetch
if you want a reset event: 在较新版本的Backbone中,如果需要重置事件,则需要传递
reset: true
选项以fetch
:
coll.fetch({ reset: true }); // This will now trigger a 'reset' event
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.