简体   繁体   中英

Rails 4 Coffee Function Not Working

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM