Question

I'm working on a Hubot adapter for my corporate chat system. The output of the following code is quite surprising, I'm not sure where to go next. There is no runtime error (as far as I can tell)

Output:

connect console
DEBUG connect logger
posted console

Code:

connect: ->
  console.log 'connect console'
  @logger.debug 'connect logger'

  @jsonClient.post 'Route/WebService/Json/Login', loginRequest, (err, res, body) ->
    console.log 'posted console'
    @logger.debug 'posted logger'
Was it helpful?

Solution

If you want @ to be the same inside the callback function as it is outside, then define the callback with a fat-arrow (=>):

@jsonClient.post 'Route/WebService/Json/Login', loginRequest, (err, res, body) =>
  #...

Keep in mind that @ (AKA this) inside a (Coffee|Java)Script function depends on how the function is called, not how or where the function is defined (unless of course you have a bound function...). If you use => to define the function then it will be bound to the current @ and @logger and @jsonClient will be what you expect them to be inside the callback.

You could also use Function.bind:

callback = (err, res, body) ->
  console.log 'posted console'
  @logger.debug 'posted logger'

@jsonClient.post 'Route/WebService/Json/Login', loginRequest, callback.bind(@)

if you wanted a native solution.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top