55

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.

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
glortho
  • 13,120
  • 8
  • 49
  • 45
  • 1
    name your anonymous functions. do it right now. you don't have proper names, so call them `f` and `g`: `f = (...) -> ...`, `g = ...`. then `( $ 'element' ).hover f, g`. so simple, so expressive. – flow Jun 24 '14 at 10:10

4 Answers4

52

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() {});
Anurag
  • 140,337
  • 36
  • 221
  • 257
  • 1
    If anybody stumbled upon this: careful not to insert a space here: `hover (`, you will end up with extra parentheses. – punund May 15 '14 at 06:42
25

Put parentheses around the anonymous functions.

Joe Cheng
  • 8,001
  • 42
  • 37
  • I swear I did this - what I was alluding to with hover( -> - but just did it again andit worked. Thanks! – glortho Jun 24 '11 at 04:03
  • 1
    It should be noted though, that there has be exactly zero whitespace between hover and the parantheses. $(@).hover() != $(@).hover () Otherwise, the output would be wrapped in another set of parantheses. –  Jul 07 '11 at 12:17
  • Not enough info in this answer, Anurag's answer better explains what to do. – ObjectNameDisplay Dec 15 '16 at 20:38
21

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
kevinhyunilkim
  • 844
  • 7
  • 5
  • Thanks, \ is very good to go. while in long lines of code, we don't need to search and find ). Using \ with , is really simple. I feel jquery while using () again. – Sudhakar Krishnan Nov 18 '13 at 07:28
8

Without parenthesis or backslash:

f ->
  0
, ->
  1

Output on 1.7.1:

f(function() {
  return 0;
}, function() {
  return 1;
});
Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985