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。


当前回答

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

在application.js

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

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

其他回答

你必须使用:

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

来自turbolinks,博士。

注意:请参阅@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');
});

或者使用

$(document).on "page:load", attachRatingHandler

或者使用jQuery的.on函数来达到同样的效果

$(document).on 'click', 'span.star', attachRatingHandler

详情请点击这里:http://srbiv.github.io/2013/04/06/rails-4-my-first-run-in-with-turbolinks.html

我发现当使用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 4文档中找到了这个,类似于DemoZluk的解决方案,但略短:

$(document).on 'page:change', ->
  # Actions to do

OR

$(document).on('page:change', function () {
  // Actions to do
});

如果你有调用$(document).ready()的外部脚本,或者如果你不想重写所有现有的JavaScript,那么这个gem允许你继续使用$(document).ready()和TurboLinks: https://github.com/kossnocorp/jquery.turbolinks