backbone.js collection.get() undefined

2019-07-21 18:29发布

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.

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

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.

Does anyone have any ideas?

1条回答
等我变得足够好
2楼-- · 2019-07-21 19:06

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. 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);

Or, for a one-shot notification, you could use the success callback:

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
查看更多
登录 后发表回答