Rails 4:如何将 $(document).ready() 与 turbo-links 一起使用 [英] Rails 4: how to use $(document).ready() with turbo-links

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

问题描述

我在尝试以rails 方式"组织 JS 文件时遇到了 Rails 4 应用程序的问题.它们以前分散在不同的视图中.我将它们组织成单独的文件并使用资产管道编译它们.但是,我刚刚了解到,当打开涡轮链接时,jQuery 的就绪"事件不会在后续点击时触发.第一次加载页面时它可以工作.但是当你点击一个链接时,ready(function($) { 中的任何东西都不会被执行(因为页面实际上不会再次加载).很好的解释:这里.

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 事件在 turbo-links 开启时正常工作的正确方法是什么?您是否将脚本包装在特定于 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:如何将 $(document).ready() 与 turbo-links 一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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