How to pass two anonymous functions as arguments in CoffeScript?

后端 未结 4 877
误落风尘
误落风尘 2020-11-29 04:06

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

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


        
相关标签:
4条回答
  • 2020-11-29 04:17

    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() {});
    
    0 讨论(0)
  • 2020-11-29 04:20

    Put parentheses around the anonymous functions.

    0 讨论(0)
  • 2020-11-29 04: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
    
    0 讨论(0)
  • 2020-11-29 04:21

    Without parenthesis or backslash:

    f ->
      0
    , ->
      1
    

    Output on 1.7.1:

    f(function() {
      return 0;
    }, function() {
      return 1;
    });
    
    0 讨论(0)
提交回复
热议问题