How to convert a jQuery function with two function arguments in Coffeescript

I want to convert a jQuery function written in JavaScript to Coffeescript, which receives two functions as parameters. I am new to Coffeescript and I am a bit stuck here. The original function is something like:

$('#target').toggle(function() { alert('First handler for .toggle() called.'); }, function() { alert('Second handler for .toggle() called.'); }); 

What does it look like in coffeescript?

+4
source share
3 answers

An easy way to see how something works in coffeescript in real time is to go to the official website and use the "Try Coffeescript" dropdown panel. One way to find it to output the same code as you would like is to do it:

 $('#target').toggle -> alert 'First handler for .toggle() called.' , -> alert 'Second handler for .toggle() called.' 

Give it a try. This may seem like a bit of a weird input code to a website, but I definitely found it useful.

+8
source
Answer

@genericdave is correct. Here's an alternative in case the lack of partners bothers you, as I do:

 $('#target').toggle( -> alert('First handler for .toggle() called.'), -> alert('Second handler for .toggle() called.') ) 
+7
source

It is also possible to have the best of both worlds: no parentheses, for example, in response to @genericdave and nice formatting, as in @ Domenic's. You will have to use the line break character: \ .

When working with single line:

 $('#target').toggle \ -> alert "First handler for .toggle() called.", -> alert "Second handler for .toggle() called." 

When accessing callbacks that contain more than one line of code:

 $('#target').toggle \ -> alert "1st handler. First line" alert "1st handler. Second line" ,-> alert "2nd handler. First line" alert "2nd handler. Second line" 
+1
source

All Articles