Array Displays Length Of 0 Sometimes
Solution 1:
I'm pretty sure that the sequence of events goes like this:
- You call
fetch
on the collection to load your data from the server. - You call
console.log(joinedGoalList)
, this is asynchronous in some browsers. - You call
joinedGoalList.where
and find an empty collection. - The
fetch
call from 1 returns and populates the collection. - The
console.log
call from 2 executes and prints out the populated collection, this call will have a reference tojoinedGoalList
and that reference will now be pointing at a populated collection.
When you do this locally, the AJAX fetch
in 4 returns quite quickly so step 4 occurs before 3 and everything behaves the way you'e expecting it to.
You have a couple options here:
fetch
has asuccess
callback:The options hash takes
success
anderror
callbacks which will be passed(collection, response)
as arguments.So you could use the
success
callback to delay whatever is callingwhere
until the server has responded and the collection is populated.fetch
resets the collection:When the model data returns from the server, the collection will reset.
and
reset
willreplace a collection with a new list of models (or attribute hashes), triggering a single
"reset"
event at the end.So you could listen for the
"reset"
event and use that event to trigger whatever is callingwhere
.
Post a Comment for "Array Displays Length Of 0 Sometimes"