Skip to content Skip to sidebar Skip to footer

Backbone.js Model.get() Returns Undefined, Scope Using Coffeescript + Coffee Toaster?

I'm writing an app using coffeescript with coffee toaster (an awesome NPM module for stitching) that builds my app.js file. Lots of my application classes and templates require i

Solution 1:

There are two things that you need to understand here:

  1. fetch is asynchronous.
  2. Some console.logs are asynchronous.

So this is what's happening:

  1. You call @user.fetch() and it launches an AJAX call.
  2. You call console.log(@user) and that does another bit of asynchronous work but (and this is a big but!), it takes a reference to @user along with it, the reference will be dereferenced when the console.log call does its logging.
  3. You call console.log(@user.get('email')), this takes along what @user.get('email')returns, the get call will be executed immediately.
  4. The AJAX call from (1) returns some stuff for @user.
  5. The console.log calls get around to logging things in the console.

The console.log from (2) carries a reference to the @user that fetch populates in (4); by the time (4) executes, @user has been populated so you see a full user in the console. When you call @user.get('email') in (3), the fetch hasn't populated @user yet so @user.get('email') is undefined and you're actually saying

console.log(undefined)

The arguments for the console.log calls will be evaluated (but the final results that are passed to console.log will not dereferenced!) when you call the function rather than when it finishes executing and puts things in the console.

So you have various asynchronous things mixing together and therein lies the confusion.

If you change your code to this:

@user = new models.User
@user.fetch(success: =>
    console.log(@user) 
    console.log(@user.get('email'))   
)

you'll get the results that you're expecting.

Post a Comment for "Backbone.js Model.get() Returns Undefined, Scope Using Coffeescript + Coffee Toaster?"