1

I am very new to this so I'm trying to follow the http://guides.rubyonrails.org/working_with_javascript_in_rails.html and the http://guides.rubyonrails.org/asset_pipeline.html Rails Guides (I'm using Rails 4)

So in views/myController I have

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

In app/assets/javascripts/myController.js.coffee the paintIt function

paintIt = (element, backgroundColor, textColor) ->
  element.style.backgroundColor = backgroundColor
  if textColor?
   element.style.color = textColor

In app/assets/javascripts/application.js I have the directive:

//= require_tree .

so the coffeescript in myController.js.coffee should be compiled

And in views/layouts/application I have the

javascript_include_tag "application"

I also checked that the coffee-rails gem is in the gemfile and installed.

However in my view I see the "Paint it red" link but the coffeescript function is not triggered. (nothing happens)

Also checked that if I write the javascript inline it does work

WHy is this? What am I missing?

7
  • 1
    coffeescript wraps the code written in each file with a closure to avoid variables from shadowing and polluting the global scope. Try adding a @ before paintIt so it will become a property of window: @paintIt = (element, backgroundColor, textColor) ->
    – akhanubis
    Sep 4, 2013 at 14:04
  • I tried that (although I didn't quite understand what it means) but It didn't seem to work
    – Vital V
    Sep 4, 2013 at 14:17
  • Try $(element).css("background-color", backgroundColor); Sep 4, 2013 at 14:21
  • 1
    The code you write in myController.js.coffee will be executed inside a function where this refers to window(@ is just a shortcut for this). Try keeping @paintIt and changing onclick to window.paintIt(this, '#990000')
    – akhanubis
    Sep 4, 2013 at 14:22
  • Hey, thanks @PabloB. I have now @paintIt and onclick=window.paintIt(this, '#990000'), but I'm afraid that didn't do the trick either. Is there a way I can actually check that the coffee is compiling to javascript and that I can access it ? ( Btw, I see the application.js is included as <script > in the html)
    – Vital V
    Sep 4, 2013 at 14:40

1 Answer 1

0

As stated in the comments, coffee-script uses with a top-level function wrapper. If you compile your file manually you can use the --bare command line option.

Else I will point you to the following post: How can I use option "--bare" in Rails 3.1 for CoffeeScript?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.