How to safelly work with Rails 5 Turbolinks + JavaScript

32 views
Skip to first unread message

Emmanuel Mtali

unread,
Oct 12, 2016, 2:02:06 AM10/12/16
to Ruby on Rails: Talk
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,

Colin Law

unread,
Oct 12, 2016, 9:23:35 AM10/12/16
to Ruby on Rails: Talk
Many use javascript and turbolinks. Unless you tell us the problem you
have then it is difficult to help.

Colin


>
> --
> You received this message because you are subscribed to the Google Groups
> "Ruby on Rails: Talk" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to rubyonrails-ta...@googlegroups.com.
> To post to this group, send email to rubyonra...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/rubyonrails-talk/06ca2e36-1e16-46f1-aac6-c6d47b106dad%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

Walter Lee Davis

unread,
Oct 12, 2016, 9:28:00 AM10/12/16
to rubyonra...@googlegroups.com
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

> On Oct 11, 2016, at 6:42 PM, Emmanuel Mtali <emmanue...@gmail.com> wrote:
>
> 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,
>
Reply all
Reply to author
Forward
0 new messages