2

我正在尝试在带有 turbolinks 5 的 rails 5.1 应用程序中执行以下操作:

$(document).on 'turbolinks:load', ->
  REFRESH_INTERVAL_IN_MILLIS = 5000
  if $('.f-pending-message').length > 0
    setTimeout (->
      Turbolinks.enableTransitionCache(true)
      Turbolinks.visit location.toString()
      Turbolinks.enableTransitionCache(false)
      return
    ), REFRESH_INTERVAL_IN_MILLIS

但我不断得到:

TypeError:Turbolinks.enableTransitionCache 不是函数。(在 'Turbolinks.enableTransitionCache()' 中,'Turbolinks.enableTransitionCache' 未定义)

我究竟做错了什么?

4

1 回答 1

2

enableTransitionCache功能仅在旧版本的 Turbolinks 中可用。它在 Turbolinks 5 中不可用 :(

目前 Turbolinks 没有刷新页面正文(并保持滚动位置)的方法,因此您必须创建自己的方法。

我在How to refresh a page with Turbolinks中对此进行了介绍。基本上,在重新访问当前页面之前存储滚动位置,然后在页面加载时恢复到该位置。在您使用 jQuery/coffeescript 的情况下:

REFRESH_INTERVAL_IN_MILLIS = 5000
timerID = null
scrollPosition = null

reload = ->
  scrollPosition = [window.scrollX, window.scrollY]
  Turbolinks.visit window.location.toString(), action: 'replace'

$(document).on 'turbolinks:load', ->
  if scrollPosition
    window.scrollTo.apply window, scrollPosition
    scrollPosition = null

  if $('.f-pending-message').length > 0
    timerID = window.setTimeout(reload, REFRESH_INTERVAL_IN_MILLIS)

$(document).on 'turbolinks:before-cache turbolinks:before-render', ->
  window.clearTimeout timerID

请注意,当页面“卸载”时,计时器会被清除,因此如果用户以给定的时间间隔导航到另一个页面,则不会重新加载页面。

或者,您可能希望仅通过 AJAX 和 js.erb 更新页面中需要它的部分,而不是重新加载正文。如果不了解更多关于您要实现的目标以及 HTML 的结构方式,很难为此编写代码,但可能值得考虑。

于 2017-06-03T11:34:32.387 回答