zishe zishe - 3 months ago 9
CoffeeScript Question

How to make callback function in Coffeescript

I can't find out how to make a function that calls another function at the end.

I want to be able to do something like this:

book.save (err) ->
MyFunc param1, param2, (callbackParam) ->
# some code using callbackParam

MyFunc = (param1, param2) ->
# some other code that defines callbackParam
?.call(callbackParam)


What has to be called and how does it receive the data?

Answer

If you want to call MyFunc as:

MyFunc param1, param2, some_function

Then it should look like this:

MyFunc = (param1, param2, callback) ->
    # some code that defines callbackParam
    callback callbackParam

And if you want to make the callback optional:

MyFunc = (param1, param2, callback) ->
    # some code that defines callbackParam
    callback? callbackParam

And if you want to supply a specific @ (AKA this), then you'd use call or apply just like in JavaScript:

MyFunc = (param1, param2, callback) ->
    # some code that defines callbackParam
    callback?.call your_this_object, callbackParam

The (callbackParam) -> ... stuff is just a function literal that acts like any other parameter, there's no special block handling like in Ruby (your tags suggest that Ruby blocks are the source of your confusion).