我在试图组织JS文件“rails方式”时遇到了Rails 4应用程序中的一个问题。他们以前分散在不同的意见。我把它们组织成单独的文件,并用资产管道进行编译。但是,我刚刚了解到,jQuery的“就绪”事件不会触发涡轮链接打开后续点击。你第一次加载一个页面的作品。但是当你点击一个链接时,内部的任何内容ready( function($) {都不会被执行(因为页面实际上并没有再次加载)。很好的解释:在这里。
所以我的问题是:什么是正确的方式来确保jQuery事件正常运行,而涡轮链接?你把脚本包装在一个Rails特定的监听器中吗?或者,也许铁轨有一些魔法,使之不必要?这个文档对于如何工作有些模糊,特别是通过像application.js这样的清单加载多个文件。
最近我发现了最简单易懂的处理方法:
$(document).on 'ready page:load', ->
# Actions to do
要么
$(document).on('ready page:load', function () {
// Actions to do
});
编辑
如果你有委托的事件绑定到document,确保你把它们附加在ready函数之外,否则它们将在每个page:load事件(导致相同的函数被多次运行)上反弹。例如,如果你有任何这样的电话:
$(document).on 'ready page:load', ->
...
$(document).on 'click', '.button', ->
...
...
把它们从ready功能中拿出来,就像这样:
$(document).on 'ready page:load', ->
...
...
$(document).on 'click', '.button', ->
...
绑定的委托事件document不需要绑定在ready事件上。
是我做的... CoffeeScript:
ready = ->
...your coffeescript goes here...
$(document).ready(ready)
$(document).on('page:load', ready)
最后一行监听页面加载,这是turbo链接将触发的。
编辑 ...添加Javascript版本(每个请求):
var ready;
ready = function() {
...your javascript goes here...
};
$(document).ready(ready);
$(document).on('page:load', ready);
编辑2 ...对于Rails 5(Turbolinks 5)page:load变得turbolinks:load甚至会在初始加载时被解雇。所以我们可以做到以下几点:
$(document).on('turbolinks:load', function() {
...your javascript goes here...
});