Google Groups

Re: [coffeescript] How do I use CoffeeScript to handle events?

Kit Cambridge Aug 3, 2011 6:36 AM
Posted in group: CoffeeScript
Try this:

    <!DOCTYPE html>
    <title>Some fresh brewed coffee</title>
    <script src=""></script>
    <script type="text/coffeescript">
    @h = h = () ->
      for num in [1..300]
        if num % 2 == 0 and num % 3 == 0
          document.write num + '*<br>'
          document.write num + '<br>'
    <p onclick="h()">Click Me</p>

The `@h` is necessary to expose the `h` function to the global scope (alternatively, you can
use `window.h`), since the CoffeeScript browser compiler wraps all `text/coffeescript` sources
inside immediately-invoked function expressions when compiling and evaluating them. Also,
you don't need to call `` in the `onclick` attribute; the CoffeeScript source is
automatically compiled to the equivalent JavaScript on page load.

On Aug 3, 2011, at 12:28 AM, wrote:

> However, when I click the paragraph tag, I get an error sent to the console
> saying that h() is not defined (which it very clearly is). Any advice?