Reputation: 12072
I'm adding few bells and whistles to my app's frontend so I'm going with coffee script.
I have a controller called "foo" and I see a file called "foo.coffee"
javascripts/foo.coffee:
$(document).on "page:change", ->
$("#bar").click ->
alert "Click"
views/foo/show.html.erb:
<%= link_to "Get Foobar!", '#', id: "bar", class: 'button' %>
Working js in application.js:
$("#bar").on("click", function(){
alert('Hey Foo!');
});
When I click the button, no alert; nothing in console. If I change the code to pure js, I get the alert. I have coffee-rails
in my Gemfile. Is there something missing? Im on rails 4.2.4
Upvotes: 1
Views: 812
Reputation: 76774
There are a number of potentialities you may have an issue with.
Firstly, you're using page:change
- this is a turbolinks hook which is essentially the stand-in for $(document).ready(....
Whilst this is not an issue in itself, I think your use of it may curtail some of the functionality in your app:
#app/assets/javascripts/foo.coffee
foo = ->
$("#bar").on "click", ->
alert "Click"
$(document).on "ready page:load", foo
The above is more along the correct way to use this type of functionality. Another would be to use delegation
from the document
object for your click
:
#app/assets/javascripts/foo.coffee
$(document).on "click", "#bar", ->
alert "Click"
Both of these methods should work to give you the functionality required. Specifically, they'll work with Turbolinks to ensure it does not impede functionality.
--
The main issue you have is likely that foo.coffee
is not being loaded.
You need to ensure that you have the following in your application.js
:
#app/assets/javascripts/application.js
// require_tree .
This will make sure all your controller JS is being called when your application runs.
Upvotes: 2