Rails 4:如何使用带有turbo-links的$(document).ready() [英] Rails 4: how to use $(document).ready() with turbo-links

查看:179
本文介绍了Rails 4:如何使用带有turbo-links的$(document).ready()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Rails 4应用程序中遇到了一个问题,同时尝试组织JS文件rails way。他们以前分散在不同的观点中。我将它们组织成单独的文件,并使用资产管道进行编译。但是,我刚刚了解到,当打开turbo-linked时,jQuery的就绪事件不会触发后续点击。第一次加载页面时它可以工作。但是当你点击链接时, ready(函数($){)内的任何内容都不会被执行(因为页面实际上没有再次加载)。好的解释: 这里

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.

所以我的问题是:在启用turbo-links时,确保jQuery事件正常工作的正确方法是什么?是否包装脚本在一个特定于Rails的监听器中?或者rails可能有一些神奇的东西使它变得不必要?文档对于它应该如何工作有点模糊,特别是关于通过像application.js这样的清单加载多个文件。

So my question is: What is the right way to ensure that jQuery events work properly while turbo-links are on? Do you wrap the scripts in a Rails-specific listener? Or maybe rails has some magic that makes it unnecessary? The docs are a bit vague on how this should work, especially with respect to loading multiple files via the manifest(s) like application.js.

推荐答案

我刚学会了解决这个问题的另一个选项。如果你加载 jquery-turbolinks gem 它会将Rails Turbolinks事件绑定到 document.ready 事件,这样你就可以用通常的方式编写jQuery。您只需在js清单文件中的 jquery 之后添加 jquery.turbolinks (默认情况下: application.js )。

I just learned of another option for solving this problem. If you load the jquery-turbolinks gem it will bind the Rails Turbolinks events to the document.ready events so you can write your jQuery in the usual way. You just add jquery.turbolinks right after jquery in the js manifest file (by default: application.js).

这篇关于Rails 4:如何使用带有turbo-links的$(document).ready()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆