使 jQuery 与 Turbolinks 一起工作 [英] Making jQuery works with Turbolinks

查看:66
本文介绍了使 jQuery 与 Turbolinks 一起工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Rails 4 应用程序,它使用 Turbolinks.我的理解是 Turbolinks 会破坏 jQuery 代码,因为 Turbolinks 不会加载新页面,而只会获取新元素.

因此,导航到新页面可能不会触发 .ready,尽管它总是触发 .page:load,因此新的 jQuery 代码不会初始化.>

我有很多 jQuery 代码,所以我不想修改我的 jQuery 代码以与 Turbolinks 兼容.

是否可以在我的 application.js 中添加覆盖 .ready 事件以包含 page:load 的 javascript 代码?我该怎么做?

解决方案

与其等待 $(document).ready 为您的 jQuery 触发,只需使用 page:load改为:

$(document).on 'page:load' -><你的代码>

或者,您可以设置 jquery.turbolinks gem:https://github.com/kossnocorp/jquery.turbolinks

I have a Rails 4 app, which uses Turbolinks. My understanding is that Turbolinks breaks jQuery code, as Turbolinks does not load new page, but only get new elements.

Therefore, navigating to new page may not trigger .ready, although it always triggers .page:load, and thus new jQuery code won't initialize.

I have a lot of jQuery code, so I don't want to modify my jQuery code to be compatible with Turbolinks.

Is it possible to add a javascript code to my application.js that overwrites .ready event to include page:load as well? How should I do it?

解决方案

Rather than wait for $(document).ready to fire for your jQuery, just use page:load instead:

$(document).on 'page:load' ->
  <your code>

Alternatively, you can set up the jquery.turbolinks gem: https://github.com/kossnocorp/jquery.turbolinks

这篇关于使 jQuery 与 Turbolinks 一起工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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