Last Updated: February 25, 2016
· luuf

Instance method callback in CoffeeScript

If you need to use an instance method on a callback in CoffeeScript when calling it from an instance method, this is an example of how you can do it:

class Dog
  fetch_later: ->
  message_for_fetch_later: ->
    alert "Ok, I will fetch that later."
  prepare_fetch_later: ->
    setTimeout((=> @fetch_later();return;),1000)

doggy = new Dog


What this does in javascript is to set a this variable to point to the object, and create a closure and run _this.fetchlater() inside that closure. The additional return is to avoid returning values.

3 Responses
Add your response

Is the only reason for the additional method, prepare_fetch_later, to have the additional return statement? I could see re-writing this simpler as the following gist:

over 1 year ago ·

@macfanatic The reason for the additional method was to call another instance method, to show that @ was pointing to the correct @ working as expected.

I also like to put timeouts that are short on a on-liner, which require the additional ().

However I like your simpler gist.

over 1 year ago ·

Ah, ok, makes sense.

over 1 year ago ·