How to pass two anonymous functions as arguments in CoffeScript?

JavascriptJqueryAnonymous FunctionCoffeescript

Javascript Problem Overview


I want to pass two anonymous functions as arguments for jQuery's hover, like so:

$('element').hover(
  function() {
    // do stuff on mouseover
  },
  function() {
    // do stuff on mouseout
  }
);

It's easy with just one – hover -> – but what is the proper syntax in CoffeeScript for two? I tried ...hover ->, ...hover( ->..., etc. but nothing gets me the above structure.

Javascript Solutions


Solution 1 - Javascript

I think the problem lies with using single line comments //. Single-line comments enclosed in /* .. */ seem to work fine. Here's an equivalent example with something other than a comment.

$('element').hover(
  -> console.log("first")
  -> console.log("second")
)

Or with comments using /* .. */.

$('element').hover(
  -> /* first */
  -> /* second */
)

You can try these examples under the Try CoffeeScript tab. CoffeeScript adds a return statement to return the last expression of the function. If you wanted bare-bones functions which do nothing and don't contain a return at the end, try:

$('element').hover(
  () ->
  () ->
)
// $('element').hover(function() {}, function() {});

Solution 2 - Javascript

Put parentheses around the anonymous functions.

Solution 3 - Javascript

Another way is to use backslash after the caller function, the comma should be indented correctly.

$('element').hover \
  -> # do stuff on mouseover
  ,
  -> # do stuff on mouseout

Solution 4 - Javascript

Without parenthesis or backslash:

f ->
  0
, ->
  1

Output on 1.7.1:

f(function() {
  return 0;
}, function() {
  return 1;
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionglorthoView Question on Stackoverflow
Solution 1 - JavascriptAnuragView Answer on Stackoverflow
Solution 2 - JavascriptJoe ChengView Answer on Stackoverflow
Solution 3 - JavascriptkevinhyunilkimView Answer on Stackoverflow
Solution 4 - JavascriptCiro Santilli Путлер Капут 六四事View Answer on Stackoverflow