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>
    <html>
    <head>
    <title>Some fresh brewed coffee</title>
    <script src="http://jashkenas.github.com/coffee-script/extras/coffee-script.js"></script>
    <script type="text/coffeescript">
    @h = h = () ->
      for num in [1..300]
        if num % 2 == 0 and num % 3 == 0
          document.write num + '*<br>'
        else
          document.write num + '<br>'
    </script>
    </head>
    <body>
    <p onclick="h()">Click Me</p>
    <br>
    <br>
    </body>
    </html>

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 `CoffeeScript.run` 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, darkli...@gmail.com 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?