Reputation: 2486
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?
Upvotes: 2
Views: 1824
Reputation: 434665
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()
.$.ajax
call.console.log(coll)
and a live reference goes in the console.coll.at(1)
or coll.get(1)
and get nothing because 2 hasn't returned from the server yet.coll
has been populated by now so the coll
reference in the console includes the models that came back in 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:
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
Upvotes: 5