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()
message_for_fetch_later: ->
alert "Ok, I will fetch that later."
prepare_fetch_later: ->
setTimeout((=> @fetch_later();return;),1000)
doggy = new Dog
doggy.prepare_fetch_later()
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.
Written by Leif Ringstad
Related protips
3 Responses
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:
@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.
Ah, ok, makes sense.