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).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")本身的行为会出乎意料——尤其是在开发过程中。

其他回答

首先,安装jquery-turbolinks gem。然后,不要忘记将包含的Javascript文件从application.html.erb的body末尾移动到它的<head>。

如本文所述,如果出于速度优化的原因将应用程序javascript链接放在页脚中,则需要将其移动到标记中,以便它在标记中的内容之前加载。这个解决方案对我很有效。

$(document).on 'ready turbolinks:load', ->
  console.log '(document).turbolinks:load'

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

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

我想我把这个留给那些升级到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

注意:请参阅@SDP的答案,以获得一个干净的内置解决方案

我修改如下:

确保你在其他依赖于应用程序的js文件被包括之前,通过改变包括顺序,如下所示:

// in application.js - make sure `require_self` comes before `require_tree .`
//= require_self
//= require_tree .

在application.js中定义一个处理绑定的全局函数

// application.js
window.onLoad = function(callback) {
  // binds ready event and turbolink page:load event
  $(document).ready(callback);
  $(document).on('page:load',callback);
};

现在你可以绑定如下内容:

// in coffee script:
onLoad ->
  $('a.clickable').click => 
    alert('link clicked!');

// equivalent in javascript:
onLoad(function() {
  $('a.clickable').click(function() {
    alert('link clicked');
});