How to safelly work with Rails 5 Turbolinks + JavaScript

I recent posted a question on StackOverflow but sadly i dint get enough attention. My question is "Can someone please tell me how can i handle problems introduced by Turbolinks on handling JavaScript??? , or i should stop using it(turbolinks)?? " Thanks,

I recent posted a question on StackOverflow but sadly i dint get enough attention. My question is "Can someone please tell me how can i handle problems introduced by Turbolinks on handling JavaScript??? , or i should stop using it(turbolinks)?? " Thanks,

Many use javascript and turbolinks. Unless you tell us the problem you have then it is difficult to help.

Colin

Looking at your question, I am wondering what this raty() method does. It seems more that the problem is there, not in Turbolinks. If your script does not set up a listener that can deal with being loaded once only, and responding to events, then it's probably not a good peer to Turbolinks.

Generally speaking, if you need to do something to the page at each load, you can change your load event to turbolinks:load. But more likely, if you refactor your method to this pattern, you won't care.

Instead of this:

  $('.rating').click(function(){     $(this).whatever...   });

Do this:

  $(document).on('.rating', 'click', function(){     $(this).whatever...   });

That will fire on every click, but only get past the first line if the click was on a .rating classed element, and then look deeper and do its thing. You don't have to re-attach this listener to the DOM at each page load, because it lives at a level where it can deal with the changes Turbolinks makes to the DOM beneath it.

Walter