4

I want to convert a jQuery function written in JavaScript into Coffeescript, which gets two functions as parameters. I'm new to Coffeescript and I'm a little stuck here. The original function is something like:

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

How does it look like in Coffeescript?

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
acme
  • 14,654
  • 7
  • 75
  • 109

2 Answers2

8

An easy way to see how something works in coffeescript in real time is to go over to the official website and use the "Try Coffeescript" dropdown pane. One way I found of getting it to output the exact same code as what you wanted was to do this:

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

Give it a try. It may feel a bit odd typing code into a website, but I've certainly found it useful.

genericdave
  • 369
  • 2
  • 5
  • Thanks! It takes a little time to get used to CoffeeScript, but it's pretty sexy nevertheless! – acme Sep 09 '11 at 08:59
7

@genericdave's answer is correct. Here's an alternative in case the lack of parens confuses you like it does me:

$('#target').toggle(
    -> alert('First handler for .toggle() called.'),
    -> alert('Second handler for .toggle() called.')
)
Domenic
  • 110,262
  • 41
  • 219
  • 271
  • Thanks! It is certainly a little bit more readable (at least when you are new to Coffeescript). – acme Sep 09 '11 at 08:59