Making jQuery works with Turbolinks

2019-04-09 21:27发布

I have a Rails 4 app, which uses Turbolinks. My understanding is that Turbolinks breaks jQuery code, as Turbolinks does not load new page, but only get new elements.

Therefore, navigating to new page may not trigger .ready, although it always triggers .page:load, and thus new jQuery code won't initialize.

I have a lot of jQuery code, so I don't want to modify my jQuery code to be compatible with Turbolinks.

Is it possible to add a javascript code to my application.js that overwrites .ready event to include page:load as well? How should I do it?

4条回答
欢心
2楼-- · 2019-04-09 21:39

i had to use the page:change event:

js:

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

coffee script:

$(document).on 'page:change', ->
    <code here>
查看更多
放我归山
3楼-- · 2019-04-09 21:46

Rather than wait for $(document).ready to fire for your jQuery, just use page:load instead:

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

Alternatively, you can set up the jquery.turbolinks gem: https://github.com/kossnocorp/jquery.turbolinks

查看更多
放我归山
4楼-- · 2019-04-09 21:52

With TurboLinks 5 / Rails 5 ... I would recommend instantiating DataTables like this.

It will prevent the heading and footer paging from showing up multiple 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
查看更多
萌系小妹纸
5楼-- · 2019-04-09 22:02

With turbolinks 5.0.0, the events changed to turbolinks:load. See full list of turbolinks events.

The documentation recommends following code:

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

The jquery.turbolinks fork located at https://github.com/dalpo/jquery.turbolinks already reflects these changes and allows for a seamless drop-in of turbolinks. Nevertheless, I would go for the turbolinks:load event to have full control and not require another library.

查看更多
登录 后发表回答