Get stuck in Working with JavaScript in Rails

I am doing the Working with JavaScript in Rails guide, but I get stuck in section

2 Unobtrusive JavaScript

When it says :

pull the function definition out of the click handler, and turn it into CoffeeScript:

paintIt = (element, backgroundColor, textColor) ->

`` = backgroundColor

``if textColor?

`` = textColor

And then on our page:

<``a href``=``"#" onclick``=``"paintIt(this, '#990000')"``>Paint it red</``a``>

When I do this I and click on the link in my chrome browser I get in the javascript console this error.

  1. Uncaught ReferenceError: paintIt is not defined (index):55
  2. onclick

Any suggestions please what I am doing wrong.


Indeed, this is expected because CoffeeScript will enclose all
generated code in an anonymous function and the documentation is not
correct in this point because it’s not really advocating for this
style. In case you really want to use this, change your CS code from
“paintIt = …” to “@paintIt = …” or “window.paintIt = …” and
that should work.