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?
The
fetch
method is an AJAX call and that means that it is asynchronous. Yourconsole.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)
orcoll.get(1)
and get nothing because 2 hasn't returned from the server yet.coll
has been populated by now so thecoll
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:Or, for a one-shot notification, you could use the
success
callback:In newer versions of Backbone, you need to pass the
reset: true
option tofetch
if you want a reset event: