im somewhat new to js or coffeescript and i cant figure out what is wrong with my script.
class Token
fetching_token = $.Deferred()
assigning_token = $.Deferred()
constructor: ->
@token = null
@got_token = $.Deferred()
fetch = ->
fetching_token.resolve({"access_token": '12355'})
assign_token = (data) =>
console.log "TOKEN (instance var): " + @token #undefined?
@token = data.access_token
assigning_token.resolve()
get_token: ->
fetch()
$.when(fetching_token).done (data) =>
assign_token(data)
$.when(assigning_token).done =>
@got_token.resolve()
undefined
t = new Token
t.get_token()
$.when(t.got_token).done ->
console.log "FETCHED TOKEN: " + t.token #gives null
Im trying to expose following interface on instance of object: token, got_token, get_token.
For some reason the @token in assign_token is undefined. I tried some combinations with fat arrow but couldnt make it to work.
Thank you in advance
This is a simple (private) function, not a method:
This is a private function that is bound to the class:
The
=>binds the function to whatever@(AKAthis) is when the function is defined. When you say this:@is the classCwhenfis being parsed sofis sort of a private class method.The important thing is that when you say this:
@insideassign_tokenwill not be an instance ofToken, it will actually beTokenitself. Your@tokenis an instance variable on instances ofTokenso of course it isn’t defined when you don’t have an instance ofTokenin@.You have a couple options:
assign_tokenan instance method. This makesassign_tokenpublicly accessible.@issue usingcallorapply. This keepsassign_tokenprivate but more cumbersome to call.The first option looks like this:
The second on is (mostly) done when you call
assign_token:Note the skinny arrow (
->) when definingassign_token, that gives you a simple function so that you can set the desired@when you call it with the function’scallmethod.