Backbone.js的collection.get()未定义 [英] backbone.js collection.get() undefined

查看:209
本文介绍了Backbone.js的collection.get()未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的骨干,我有一个集合全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:


  1. 您拨打 coll.fetch()

  2. 骨干发射一个 $。阿贾克斯电话。

  3. 您拨打的console.log(科尔)和现场参考的推移在控制台中。

  4. 您拨打 coll.at(1) coll.get(1)键,什么也得不到,因为<强> 2 还没有从服务器返回呢。

  5. 2 从服务器回来并填充您的收藏。

  6. 然后你去看看控制台,但科尔现在已被填充所以在控制台中的科尔参考包括回来在模型中的 5

  7. 混乱。

  1. You call coll.fetch().
  2. Backbone sends off a $.ajax call.
  3. You call console.log(coll) and a live reference goes in the console.
  4. You call coll.at(1) or coll.get(1) and get nothing because 2 hasn't returned from the server yet.
  5. 2 comes back from the server and populates your collection.
  6. Then you go look at the console but coll has been populated by now so the coll reference in the console includes the models that came back in 5.
  7. 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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆