Creating jQuery with Turbolinks

I have a Rails 4 application that uses Turbolinks. I understand that TurbolinksjQuery code breaks because Turbolinks does not load a new page, but only receives new elements.

Consequently, going to a new page may not cause .ready, although it always calls .page:load, and therefore, the new jQuery code will not be initialized.

I have a lot of jQuery code, so I don’t want to change jQuery code to be compatible with Turbolinks.

Is it possible to add javascript code to my application.js that overwrites the event .readyto be included page:load? How should I do it?

+4
source share
4

, $(document).ready jQuery, page:load :

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

jquery.turbolinks gem: https://github.com/kossnocorp/jquery.turbolinks

+4

turbolinks 5.0.0 turbolinks:load. . turbolinks.

:

document.addEventListener("turbolinks:load", function() {
  // ...
})

jquery.turbolinks, https://github.com/dalpo/jquery.turbolinks, turbolinks. , turbolinks:load, .

+3

I had to use the event page:change:

JS:

$(document).on('page:change', function () {
    <code here>
});

coffee script:

$(document).on 'page:change', ->
    <code here>
+2
source

With TurboLinks 5 / Rails 5 ... I would recommend creating DataTables instances this way.

This will prevent the paging of the header and footer several times when the back button is used.

$(document).on 'turbolinks:load', ->
  tableElementIds = [
    '### TABLE ID HERE ###'
  ]
  i = 0
  while i < tableElementIds.length
    tableElementId = tableElementIds[i]
    if $.isEmptyObject($.find(tableElementId))
      i++
      continue
    table = undefined
    if $.fn.DataTable.isDataTable(tableElementId)
      table = $(tableElementId).DataTable()
    else
      table = $(tableElementId).DataTable(### OPTIONS HERE ###)

    document.addEventListener 'turbolinks:before-cache', ->
      table.destroy()
      return

    i++

  return
+1
source

All Articles