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.

所以我的问题是:什么是确保jQuery事件在涡轮链接打开时正常工作的正确方法?您是否将脚本包装在特定于rails的侦听器中?或者也许rails有某种魔力,使它变得不必要?文档对这应该如何工作有点模糊,特别是关于通过manifest(s)加载多个文件,如application.js。


当前回答

我发现当使用ready和turbolinks的函数时,我的函数翻了一番:load,所以我使用,

var ready = function() {
  // you code goes here
}

if (Turbolinks.supported == false) {
  $(document).on('ready', ready);
};
if (Turbolinks.supported == true) {
  $(document).on('turbolinks:load', ready);
};

这样,如果支持涡轮链接,您的函数就不会加倍!

其他回答

根据新的rails指南,正确的方法是这样做:

$(document).on('turbolinks:load', function() {
   console.log('(document).turbolinks:load')
});

或者在coffeescript中:

$(document).on "turbolinks:load", ->
alert "page has loaded!"

不监听事件$(document)。就绪后,只会触发一个事件。没有惊喜,不需要使用jquery。turbolinks宝石。

这不仅适用于rails 5,而且适用于rails 4.2及以上版本。

我发现下面的文章对我来说非常有用,并详细介绍了以下用法:

var load_this_javascript = function() { 
  // do some things 
}
$(document).ready(load_this_javascript)
$(window).bind('page:change', load_this_javascript)

测试了这么多的解决方案,终于得出了这个结论。 你的代码肯定不会被调用两次。

var has_loaded = false; Var ready = function() { 如果(! has_loaded) { has_loaded = true; // YOURJS } } $(文档)时(准备); 美元(文档)。绑定(“页面:改变”,准备);

以下是我所做的,以确保事情不会执行两次:

$(document).on("page:change", function() {
     // ... init things, just do not bind events ...
     $(document).off("page:change");
});

我发现使用jquery-turbolinks gem或组合$(document)。Ready和$(document).on("page:load")或使用$(document).on("page:change")本身的行为会出乎意料——尤其是在开发过程中。

我是这么做的… CoffeeScript:

ready = ->

  ...your coffeescript goes here...

$(document).ready(ready)
$(document).on('page:load', ready)

最后一行监听页面加载,这是什么涡轮链接将触发。

编辑……添加Javascript版本(每个请求):

var ready;
ready = function() {

  ...your javascript goes here...

};

$(document).ready(ready);
$(document).on('page:load', ready);

编辑2…对于Rails 5 (Turbolinks 5)页面:load变成了Turbolinks:load,甚至会在初始加载时触发。所以我们可以这样做:

$(document).on('turbolinks:load', function() {

  ...your javascript goes here...

});