Backbone.js Model.get() Returns Undefined, Scope Using Coffeescript + Coffee Toaster?
Solution 1:
There are two things that you need to understand here:
fetch
is asynchronous.- Some
console.log
s are asynchronous.
So this is what's happening:
- You call
@user.fetch()
and it launches an AJAX call. - 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 theconsole.log
call does its logging. - You call
console.log(@user.get('email'))
, this takes along what@user.get('email')
returns, theget
call will be executed immediately. - The AJAX call from (1) returns some stuff for
@user
. - 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?"