PJAX / Back-Button destroys Datatables

datatables, pjax, rack, ruby-on-rails-3.2

Solution

I found a working solution hopefully without unforeseen problems.

$(document).ready ->
  initLeagueIndexDataTable()

$(document).on 'pjax:end', ->
  initLeagueIndexDataTable()

initLeagueIndexDataTable : ->
  if ($('#league_index').length > 0 && !$('#league_index_wrapper').length > 0)
    $('#league_index').dataTable({
      'sPaginationType': 'full_numbers',
      'bJQueryUI': true,
      'bProcessing': true,
      'bServerSide': true,
      'sAjaxSource': $('#league_index').data('source'),
      'aoColumnDefs': [
        { "bSortable": false, "aTargets": [ 1 ] },
        { "bSortable": false, "aTargets": [ 2 ] },
        { "bSortable": false, "aTargets": [ 3 ] },
        { "bSortable": false, "aTargets": [ 4 ] },
        { "bSortable": false, "aTargets": [ 5 ] }
      ],
      'bFilter': false,
      'iDisplayLength': 25,
      'bDestroy': true
    })

Problem

In our Rails 3.2 App with rack-pjax enabled appears the following Problem: - You click on a link, a page with datatable in it loads trough pjax. Everything is fine. - You click on antoher link the page "whatever" loads. - You hit the back-button the datatables page loads. BUT the datatable is not working. Sometimes it loads 2 Tables (with no data in it), sometimes it loads just the old datatable. but its not possible to manipulate the data (searching, go to page 2 etc.). Its completly static. The Data for the table is served via json (server-side processing) from the rails part of the app. We've already tried to destroy and rebuild the datatable on "pjax:start" or "pjax:end" Thanks for your Help :)

Original source