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。


当前回答

你必须使用:

document.addEventListener("turbolinks:load", function() {
  // your code here
})

来自turbolinks,博士。

其他回答

我想我把这个留给那些升级到Turbolinks 5的人:修复代码的最简单的方法是从:

var ready;
ready = function() {
  // Your JS here
}
$(document).ready(ready);
$(document).on('page:load', ready)

to:

var ready;
ready = function() {
  // Your JS here
}
$(document).on('turbolinks:load', ready);

参考:https://github.com/turbolinks/turbolinks/issues/9 # issuecomment - 184717346

以上这些都不适合我,我没有使用jQuery的$(document)来解决这个问题。ready,但使用addEventListener代替。

document.addEventListener("turbolinks:load", function() {
  // do something
});

我通常为我的rails项目做以下工作:

在application.js

function onInit(callback){
    $(document).ready(callback);
    $(document).on('page:load', callback);
}

然后在其余的.js文件中,我调用onInit(function(){})而不是使用$(function (){})

我是这么做的… 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...

});
$(document).ready(ready)  

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