Turbolinks 缓存前后的 Javascript DOM 事件 [英] Javascript DOM events before and after Turbolinks cache

查看:59
本文介绍了Turbolinks 缓存前后的 Javascript DOM 事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里有:

$(document).on 'turbolinks:load', ->
  console.log "page has loaded!"
  $ ->
    $("button#show-hide").click (e) ->
      e.preventDefault()

这使我的 click 事件仅在 Turbolinks 缓存页面后可用.我可以做 $(document).on 'turbolinks:before-visit 这将使事件仅在 Turbolinks 缓存之前可用.我应该如何让活动始终可用?

which makes my click event available only after Turbolinks caches page. I can do $(document).on 'turbolinks:before-visit which will make event available only before Turbolinks caches. How should I make event available at all times?

推荐答案

我认为这里的问题是您绑定到两个事件:turbolinks:load$(document).ready().

I think the problem here is that you are binding to two events: turbolinks:load and $(document).ready().

Turbolinks 不会丢弃 document 上的事件侦听器,因此您可以安全地将点击处理程序绑定到它,它们将被称为跨页面加载.来自 Turbolinks 文档:

Turbolinks does not discard event listeners on the document so you can safely bind click handlers to it and they will be called scross page loads. From the Turbolinks documentation:

如果可能,请避免使用 turbolinks:load 事件将事件侦听器直接添加到页面正文上的元素.相反,请考虑使用事件委托在文档或窗口上注册一次事件侦听器.

When possible, avoid using the turbolinks:load event to add event listeners directly to elements on the page body. Instead, consider using event delegation to register event listeners once on document or window.

考虑到这一点,您可以:

With this in mind, you can do:

$(document).on 'click', "button#show-hide", (e) ->
  e.preventDefault()

这篇关于Turbolinks 缓存前后的 Javascript DOM 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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