Skip to content Skip to sidebar Skip to footer

Why Is Backbone.js Returning An Empty Array When Accessing Models?

I have a router accessing its collection. My for loop wasn't iterating through the models so I tried logging the collection to see what it returned. Turns out when I log the collec

Solution 1:

Jim,

This doesn't fix your problem - you've worked that out. But it explains why you're seeing the console output you see.

When you run console.log(this), you output the object itself and the console links references (pointers if you like) to the inner variables.

When you're looking at it in the console, at the time the console.log(this) runs the models area is empty, but at the time you look at the logs, the collection has finished loading the models and the inner array variable is updated, AND the reference to that variable in the object log shows the current content.

Basically in console.log(this),inner models variable continues its normal life and the console shows the current status at the time you're looking at it, not at the time you called it. With console.log(this.models), the array is dumped as is, no reference is kept and all the inner values are dumped one by one..

That behaviour is quite simple to reproduce with a short timeout, see this fiddle.. http://jsfiddle.net/bendog/XVkHW/

Solution 2:

I found that I needed to listen for the collection to reset. So instead of passing the model into the view I created another view expecting the collection and listened for the 'reset' event to fire 'render' for the view.

# RoutersclassDraft.Routers.ShotsextendsBackbone.Routerroutes:''            : 'index''shots/:id'   : 'show'initialize: ->
    @collection = new Draft.Collections.Shots()
    @collection.fetch()

  index: ->
    view = new Draft.Views.Desktop(collection:@collection)

# ViewsclassDraft.Views.DesktopextendsBackbone.Viewel:$("body")

  initialize: ->
    @collection.on("reset",@render,this)

  render: ->
    console.log @collection
    console.log @collection.length

Solution 3:

You can use a promise. (.done will do fine)

@collection.fetch().done =>
  for model in @collection.models
    console.log model

this will give you @collection's models fetched and ready to go.

or if you don't need to force the app to wait,

@collection.on 'sync', =>
  for model in @collection.models
    console.log model

Both of these will let you do what you want.

Post a Comment for "Why Is Backbone.js Returning An Empty Array When Accessing Models?"