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 separ
$(document).ready(ready)
$(document).on('turbolinks:load', ready)
Either use the
$(document).on "page:load", attachRatingHandler
or use jQuery's .on function to achieve the same effect
$(document).on 'click', 'span.star', attachRatingHandler
see here for more details: http://srbiv.github.io/2013/04/06/rails-4-my-first-run-in-with-turbolinks.html
Instead of using a variable to save the "ready" function and bind it to the events, you might want to trigger the ready
event whenever page:load
triggers.
$(document).on('page:load', function() {
$(document).trigger('ready');
});
Tested so many solution finally came to this. This many your code is definitely not called twice.
var has_loaded=false;
var ready = function() {
if(!has_loaded){
has_loaded=true;
// YOURJS here
}
}
$(document).ready(ready);
$(document).bind('page:change', ready);
I found the following article which worked great for me and details the use of the following:
var load_this_javascript = function() {
// do some things
}
$(document).ready(load_this_javascript)
$(window).bind('page:change', load_this_javascript)
I found my functions doubled when using a function for ready
and turbolinks:load
so I used,
var ready = function() {
// you code goes here
}
if (Turbolinks.supported == false) {
$(document).on('ready', ready);
};
if (Turbolinks.supported == true) {
$(document).on('turbolinks:load', ready);
};
That way your functions don't double if turbolinks is supported!