Question

I'm having an issue where Turbolinks will bind events multiple times when using the back/forward buttons through the browser. I have a simple script to make sure it wasn't the way I have been writing my document.on() events, so...

$(document).on 'page:load', ->
  alert 'Loaded'

Will fire once when clicking a link. Clicking back or forward (or another Turbolink link) it will fire twice. Next time it'll fire a bunch of times and it keeps growing. This is my only thing I have in my manifest file outside of jQuery and Turbolinks. How do you prevent Turbolinks from duplicating event bindings?

Was it helpful?

Solution

The issue seemed to be including the javascript_tag at the end of my body, rather than the head. When in the body, the Javascript was getting removed/added every Turbolinks page:change so the bindings kept piling on.

OTHER TIPS

That makes sense - the same problem will occur if you are using the jquery-turbolinks gem, since it will cause any code inside your jQuery document ready function to run on each page load. Because the document object is never reinitialized with Turbolinks, this results in redundant bindings. The solution for this case is to place your $(document).on bindings outside of your jQuery ready function so they aren't executed on each page load.

I had the same problem and basically what I did was query if a variable was defined before including the JS. Sound a bit messy thought...

I ran into the same issue and the problem was the markup I was generating on the layout wasn't correct. I was closing the body tag in a place I shouldn't

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top