Backbone.js的collection.get()未定义 [英] backbone.js collection.get() undefined
问题描述
我使用的骨干,我有一个集合全7款车型。
I'm using Backbone, and I have a collection full of 7 models.
我要抢一个模型,并从集合拉出。然而,一切我尝试返回未定义
。
I want to grab one model and pull it from the collection. However, everything I try returns undefined
.
下面是如何我填充集合
var coll = new TestCollection();
coll.fetch();
一个简单的控制台通话记录显示,收集从JSON文件填充
A simple console log call shows that the collection is populated from the JSON file
child
_byCid: Object
_byId: Object
_onModelEvent: function () { [native code] }
_removeReference: function () { [native code] }
length: 7
models: Array[7]
__proto__: ctor
不过,我已经尝试了一大堆的方式,以抓住从集合包括 coll.at(1)
和这些车型之一coll.get(1)
但每次返回未定义
。
有没有人有什么想法?
推荐答案
取
方法是AJAX调用,这意味着,它是异步的。你的的console.log
调用把一个生动的引用到控制台(所以它是有点异步),所以你最终这一系列的事件:
The fetch
method is an AJAX call and that means that it is asynchronous. 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:
- 您拨打
coll.fetch()
。 - 骨干发射一个
$。阿贾克斯
电话。 - 您拨打
的console.log(科尔)
和现场参考的推移在控制台中。 - 您拨打
coll.at(1)
或coll.get(1)
键,什么也得不到,因为<强> 2 还没有从服务器返回呢。 - 2 从服务器回来并填充您的收藏。
- 然后你去看看控制台,但
科尔
现在已被填充所以在控制台中的科尔
参考包括回来在模型中的 5 - 混乱。
- You call
coll.fetch()
. - Backbone sends off a
$.ajax
call. - You call
console.log(coll)
and a live reference goes in the console. - You call
coll.at(1)
orcoll.get(1)
and get nothing because 2 hasn't returned from the server yet. - 2 comes back from the server and populates your collection.
- Then you go look at the console but
coll
has been populated by now so thecoll
reference in the console includes the models that came back in 5. - Confusion.
一个成功的 取
触发如果你想知道的集合被填充时复位
事件,所以你应该听该事件:
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:
coll.on('reset', this.some_method);
或者,对于一次性通知,您可以使用成功
回调:
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:
coll.fetch({ reset: true }); // This will now trigger a 'reset' event
这篇关于Backbone.js的collection.get()未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!