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: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

其他回答

最近,我发现了一种最简单易懂的处理方法:

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

OR

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

编辑 如果您已经将事件委托给文档绑定,请确保将它们附加在ready函数之外,否则它们将在每个页面上反弹:load事件(导致相同的函数多次运行)。例如,如果你有这样的电话:

$(document).on 'ready page:load', ->
  ...
  $(document).on 'click', '.button', ->
    ...
  ...

将它们从ready函数中取出,像这样:

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

$(document).on 'click', '.button', ->
  ...

绑定到文档的委托事件不需要绑定到就绪事件上。

你必须使用:

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

来自turbolinks,博士。

$(document).ready(ready)  

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

我刚知道另一个解决这个问题的方法。如果你加载jquery-turbolinks宝石,它会将Rails Turbolinks事件绑定到文档上。ready事件,这样你就可以用通常的方式编写jQuery。你只需要添加jquery。在js的manifest文件(默认:application.js)中,Turbolinks就在jquery之后。