I ran into an issue in my Rails 4 app while trying to organize JS files "the rails way". They were previously scattered across different views. I organized them into separate files and compile them with the assets pipeline. However, I just learned that jQuery's "ready" event doesn't fire on subsequent clicks when turbo-linking is turned on. The first time you load a page it works. But when you click a link, anything inside the ready( function($) {
won't get executed (because the page doesn't actually load again). Good explanation: here.
So my question is: What is the right way to ensure that jQuery events work properly while turbo-links are on? Do you wrap the scripts in a Rails-specific listener? Or maybe rails has some magic that makes it unnecessary? The docs are a bit vague on how this should work, especially with respect to loading multiple files via the manifest(s) like application.js.
Instead of using a variable to save the "ready" function and bind it to the events, you might want to trigger the
ready
event wheneverpage:load
triggers.Tested so many solution finally came to this. This many your code is definitely not called twice.
I usually do the following for my rails 4 projects:
In
application.js
Then in the rest of the .js files, instead of using
$(function (){})
I callonInit(function(){})
I found the following article which worked great for me and details the use of the following:
Here's what I do... CoffeeScript:
last line listens for page load which is what turbo links will trigger.
Edit...adding Javascript version (per request):
Edit 2...For Rails 5 (Turbolinks 5)
page:load
becomesturbolinks:load
and will be even fired on initial load. So we can just do the following: