Turbolinks.enableTransitionCache is not a function

724 views Asked by At

I'm trying to do the following in a rails 5.1 app with turbolinks 5:

$(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

But I keep on getting:

TypeError: Turbolinks.enableTransitionCache is not a function. (In 'Turbolinks.enableTransitionCache()', 'Turbolinks.enableTransitionCache' is undefined)

What am I doing wrong?

1

There are 1 answers

0
Dom Christie On BEST ANSWER

The enableTransitionCache function is only available in older versions of Turbolinks. It is not available in Turbolinks 5 :(

Currently Turbolinks doesn't have a method to refresh the body of a page (and maintain the scroll position), so you'll have to create your own.

I have covered this in How to refresh a page with Turbolinks. Basically, store the scroll position before revisiting the current page, then restore to that position when the page loads. In your case with 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

Note that the timer is cleared when the page "unloads", so that the page is not reloaded if the user navigates to another page with the given interval.

Alternatively, rather than a reloading the body, you may wish to only update the parts of the page that need it via AJAX and js.erb. It is difficult to write code for this without knowing a bit more about what you are trying to achieve, and how your HTML is structured, but it might be worth considering.