1

In my Rails 4.1 app I'm using JQuery-ujs to update cells in a table in my comments#index view. So in my comments.js.coffee file I have

jQuery ->
    $('tbody').on 'click', '.btn-info', ->
      $(this).closest('tr').children('td').eq(4).attr("id", "target")

and the corresponding update.js.erb file

$('#target').html("<%=j @comment.state.humanize %>").removeAttr("id")

The view renders different groups of comments into the table via custom routes of the form /comments/pending, /comments/confirmed etc. and all goes well so long as I request the view directly in the browser address bar.

But I also have breadcrumb links on the page which are generated via link_to helpers:

<ol class="breadcrumb">
   <li class="active">
      <a href="/comments/pending">pending</a>
   </li>
   <li>
      <a href="/comments/confirmed">confirmed</a>
   </li>
   <li>
      <a href="/comments/notable">notable</a>
  </li>
  <li>
      <a href="/comments/eminent">eminent</a>
  </li>
</ol>

When I click on any of these links to get the view, the page is correctly loaded, but inspection shows that no click handler is attached to the <tbody> element. (It is attached if I reload the page however.)

How can I ensure that the click handler is always attached?

TimP
  • 21
  • 4
  • 1
    I think we've come across the same problem. Rails has a "feature" called "Turbolinks" where it will AJAX-load pages (to be quicker), but this means the new DOM elements inserted by AJAX won't have event handlers attached. Our solution was to turn them off. Otherwise you'll have to listen for the ajax event and re-apply event handlers. – christian314159 Jun 13 '14 at 05:45
  • Thanks for the reply. I had actually seen your earlier post but failed to twig that it related here due to my inexperience. – TimP Jun 14 '14 at 00:50

1 Answers1

0

It's happening because of turbolinks. If you look into rail guides it states:

Turbolinks will make an Ajax request for the page, parse the response, and replace the entire <body> of the page with the <body> of the response. You jquery code would be in head i guess and hence it doesn't get load on clicking link.

The solution to your problem would be to wrap your jquery code inside a function and then call that function on page load like:

$(document).ready(your_function);
$(document).on('page:load', your_function);

OR

You can use the jquery-turbolinks gem which will bind the Rails Turbolink events to the document.ready events so you can write your jQuery in the usual way. For more information checkout my answer here

Community
  • 1
  • 1
Mandeep
  • 9,093
  • 2
  • 26
  • 36
  • Thanks so much for taking the trouble to reply. Sorry it's a known issue---traps for new players. I'd cruised past the brief mention in the Guides and it came back to bite me. – TimP Jun 14 '14 at 00:57