0

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'
James L
  • 16,456
  • 10
  • 53
  • 70
  • What is surprising? That there's no `@logger.debug 'posted logger'` output? What context does `@jsonClient.post` use when calling its callbacks? – mu is too short Jan 16 '14 at 17:37
  • @muistooshort yes that's what's surprising to me. In fact, this example is simplified. In reality I want to make another http call in the continuation, but nothing seems to happen. Context? No idea. I instantiate jsonClient in the ctor of the local class - does that answer the question? – James L Jan 16 '14 at 20:53

1 Answers1

1

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.

mu is too short
  • 426,620
  • 70
  • 833
  • 800