Making jQuery works with Turbolinks

两盒软妹~` 提交于 2019-12-06 04:57:46

问题


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?


回答1:


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




回答2:


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.




回答3:


i had to use the page:change event:

js:

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

coffee script:

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



回答4:


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


来源:https://stackoverflow.com/questions/19043134/making-jquery-works-with-turbolinks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!