Reputation: 19
So I have a new Rails 4 App using foundation and I started to integrate DataTables today and ran into one minor setback after setting it up to page using ajax calls.
When I click a link from one page (home in this instance) that sends me to a page that contains the datatables, the tables render without any entries or search box or pagination etc. However, if I refresh my browser, the page will fully refresh and the ajax call is made and the the table populates correctly.
After looking at the network traffic, I'm seeing that after clicking the link the response is 304: Not Modified. Since none of the other requests for the JS and CSS and etc, I'm assuming that the JS doesn't reload and make the proper ('#tasks').dataTable({...}) call.
Also, one thing to note is that the table is residing within a partial 'tasks_index.html.haml'.
One thing I did remember however was that I was still using the Turbolinks gem. I tried disabling it to see if that would fix my problem and surprisingly enough, it did.
So what would cause Turbolinks to prevent normal javascript to load on the page? Is there any way to force turbolinks to always load certain pages? Am I better off not even using Turbolinks?
Upvotes: 2
Views: 3057
Reputation: 533
I successfully used the following CoffeeScript code to make DataTables work correctly on Rails 5 / Turbolinks 5.
If you use this script, you will no longer have the problem where the DataTables wrapper reloads after you hit the back button on your browser.
Please note that I also am using the turbolinks-compatibility script.
I'm hopeful this will help someone else who is Googling / struggling with this like I was.
TurboLinks is great for speed ... but it makes loading JavaScript a pain.
$(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
Upvotes: 0
Reputation: 11
Just like lunr said, you have to put $(document).on "turbolinks:load", ->
in your .coffee file
Upvotes: 1
Reputation: 5269
I guess you are using the $(document).ready
event to initialize the datatables. When using turbolinks when you click a link this event won't fire because turbolinks loads the page itself. So you should use the document page:change
event instead. See here: http://guides.rubyonrails.org/working_with_javascript_in_rails.html#page-change-events
Upvotes: 1