Rails 开启 Turbolinks 后,事件绑定问题如何解决?

sessionstart · 2016年12月17日 · 最后由 hww 回复于 2016年12月17日 · 1719 次阅读

遇到了一个坑,开了 turbolinks 后,页面第一次加载进来的时候,点击返回顶部按钮运行正常,再切到别的页面,再点击就不行了。大神们有什么比较好的解决方式吗?

$(document).on 'ready page:load', -> # 加载且缓存。
  App.config()
  App.init()
  return
$(document).on 'page:change turbolinks:load', -> # 页面 change 后执行。
  if App.weixin()
    $('body').on 'click touchstart mousedown', 'a[href*="https://itunes.apple.com"]', (e) ->
      e.stopPropagation()
      e.preventDefault()
      $('#wechat-modal').modal 'show'
      return
  switch true
    when $('body.photos').length > 0
      photo = new (App.Photo)
      if $('.photos.index').length > 0
        photo.uploader()
        photo.index currentPage
    when $('body.episodes').length > 0
      episode = new (App.Episode)
      if $('.episodes.index').length > 0
        episode.index currentPage
      else if $('.episodes.show').length > 0
        App.hide_nav()
        episode.show episodeId
    when $('body.orders').length > 0
      order = new (App.Order)
      if $('.orders.index').length > 0
        order.index currentPage
      else if $('.orders.show').length > 0
        App.hide_nav()
        order.show orderId
  return

你的代码是什么?

楼主的初始化代码可能放错位置了,turbolinks 页面切换时,不会重新加载全部 js,你要按 turbolinks 推荐的方式来初始化。建议看 turbolinks 文档,不行的话,贴代码到论坛里面来吧。

参考这个看一下 init 。还有就是遇到坑再去翻一下 Readme

需要 登录 后方可回复, 如果你还没有账号请 注册新账号