0

I think I'm missing out on some fundamental aspect of how Javascript is handled by Rails.

I created a new Rails project using Ruby 2.1.0.

$ mkdir whatishappening
$ cd whatishappening
$ rails new .
$ rails generate scaffold post title body:text
$ rails db:migrate
$ rails server

I then proceeded to create a test post. After that I added:

whatishappening/app/views/posts/show.html.erb

<a href="#" id="foo">link</a>

whatishappening/app/assets/javascripts/posts.js (I renamed this from posts.js.coffee)

console.log("posts.js loaded");

$("#foo").on("click", function(event) {
  console.log("link clicked");
});

When I run via rails server and monitor the Javascript console in Chrome, I see:

> posts.js loaded

However, I don't see

> link clicked

when I click the link.

Can someone explain what's happening?

franksort
  • 3,093
  • 2
  • 19
  • 27

2 Answers2

2

You can check two things.

  • You added jQuery successfully, you can find how to added jQuery here.

  • Your binding code executes when foo is added to DOM, you can use document.ready to ensure that.

    console.log("posts.js loaded");
    
    $(document).ready(function(){
     $("#foo").on("click", function(event) {
        console.log("link clicked");
      });
    });
    
Community
  • 1
  • 1
Adil
  • 146,340
  • 25
  • 209
  • 204
  • 3
    you need `$(document).on('page:load', ready)` if you use `turbo-links` – Roman Kiselenko Feb 06 '14 at 12:32
  • if you use `turbo-links` you need not only @Monk_Code's code (useful tip sure) but also you need to read this article http://staal.io/blog/2013/01/18/dangers-of-turbolinks/ – trushkevich Feb 08 '14 at 13:14
2

Using the answer from @Adil and the tip from @Monk_Code, I found the following the be the best solution considering that the default Rails 4 install includes Turbolinks.

app/assets/javascripts/posts.js

console.log("posts.js loaded");

var ready;
ready = function() {

  $("#foo").on("click", function(event) {
    console.log("link clicked");
  });

};

$(document).ready(ready);
$(document).on("page:load", ready);
franksort
  • 3,093
  • 2
  • 19
  • 27