Skip to content Skip to sidebar Skip to footer

Array Displays Length Of 0 Sometimes

I am having an extremely bizarre problem. I have a Backbone collection, and I am using the where method to find models in the collection that match a certain attribute. My problem

Solution 1:

I'm pretty sure that the sequence of events goes like this:

  1. You call fetch on the collection to load your data from the server.
  2. You call console.log(joinedGoalList), this is asynchronous in some browsers.
  3. You call joinedGoalList.where and find an empty collection.
  4. The fetch call from 1 returns and populates the collection.
  5. The console.log call from 2 executes and prints out the populated collection, this call will have a reference to joinedGoalList 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:

  1. fetch has a success callback:

    The options hash takes success and error callbacks which will be passed (collection, response) as arguments.

    So you could use the success callback to delay whatever is calling where until the server has responded and the collection is populated.

  2. fetch resets the collection:

    When the model data returns from the server, the collection will reset.

    and reset will

    replace 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 calling where.

Post a Comment for "Array Displays Length Of 0 Sometimes"