简体   繁体   English

骨架.js collection.get()未定义

[英]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调用将实时引用放入控制台中(因此它是异步的),因此您会遇到以下事件序列:

  1. You call coll.fetch() . 您调用coll.fetch()
  2. Backbone sends off a $.ajax call. 骨干网发出$.ajax呼叫。
  3. You call console.log(coll) and a live reference goes in the console. 您调用console.log(coll) ,然后在控制台中添加实时引用。
  4. You call 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
  5. 2 comes back from the server and populates your collection. 2从服务器返回并填充您的集合。
  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 . 然后,您查看控制台,但是coll已经被填充,因此控制台中的coll引用包括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: 成功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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM