0

I cannot get CoffeeScript working with Rails. This is the first time I'm using CoffeeScript and I'm also fairly new with Rails too, so I don't know how to make this simple CoffeeScript function to work in the right way. Below is my people.js.coffee file at app/assets/javascript directory.

myFunction = ->
alert "test"

The alert “test” message only shows up when I load the page (app/views/people.html.erb and _form.html.erb partial); not when I click the below button in the form:

<%= submit_tag "Test CoffeeScript", :type => 'button', 
:id => 'coffeeScript', :onclick => 'myFunction()' %> 

I don't know why this strange behaviour is happening. Why :onclick is not working? The generated source code for the button should be ok:

  <input id="coffeeScript" name="commit" onclick="myFunction()" 
type="button" value="Test CoffeeScript" /> 

Below is my application.js file at app/assets/javascript.

...
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .

My Ruby version is 2.1.0 Here are some values when I ran bundle show command:

  • coffee-rails (4.0.1)
  • coffee-script (2.2.0)
  • coffee-script-source (1.7.0)
  • jbuilder (1.5.3)
  • jquery-rails (3.1.0)
  • rails (4.0.2)
  • railties (4.0.2)
  • sass (3.2.19)
  • sass-rails (4.0.3)
  • sprockets (2.11.0)
  • sprockets-rails (2.0.1)
  • turbolinks (2.2.2)

My JavaScript files are working ok; I tried similar type of function in JavaScript and it was ok.

jyrkim
  • 2,849
  • 1
  • 24
  • 33

1 Answers1

3

It's because the function is in another scope. You can do it either with unobtrusive jquery.

$ ->
  myFunction = ->
    alert("test")

  $("#coffeeScript").on "click", ->
    myFunction()

And remove the onclick handler from

<%= submit_tag "Test CoffeeScript", type: 'button', id: 'coffeeScript' %> 

or...

root = exports ? this
root.myFunction = () -> alert("test!")

I'd recommend the first one, but that is just my opinion though. Also, you have to be very careful about indentation in CoffeeScript, it works a lot like Python, whitespace matters.

An explanation on scopes and js/coffee is here How do I define global variables in CoffeeScript?

Community
  • 1
  • 1
Eyeslandic
  • 14,553
  • 13
  • 41
  • 54