Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass two anonymous functions as arguments in CoffeScript?

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.

like image 826
glortho Avatar asked Jun 24 '11 03:06

glortho


People also ask

Can you transfer an anonymous function to another function as an argument?

They're called anonymous functions because they aren't given a name in the same way as normal functions. Because functions are first-class objects, we can pass a function as an argument in another function and later execute that passed-in function or even return it to be executed later.

Can you pass a anonymous function as an argument to another function in JavaScript?

Summary. Anonymous functions are functions without names. Anonymous functions can be used as an argument to other functions or as an immediately invoked function execution.

How do you call a function in CoffeeScript?

You can simply invoke a function by placing parenthesis after its name as shown in the following example. // Generated by CoffeeScript 1.10. 0 (function() { var add; add = function() { var a, b, c; a = 20; b = 30; c = a + b; return console. log("Sum of the two numbers is: " + c); }; add(); }).

Do anonymous functions get hoisted?

Anonymous functions are never hoisted (loaded into memory at compilation). Named functions are hoisted (loaded into memory at compilation). When invoking an anonymous function, you can only call it after the declaration line. A name function can be invoked before declaration.


2 Answers

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() {}); 
like image 147
Anurag Avatar answered Sep 18 '22 13:09

Anurag


Put parentheses around the anonymous functions.

like image 23
Joe Cheng Avatar answered Sep 20 '22 13:09

Joe Cheng