问题
I'm using jQuery DataTables in a new Rails 4.2 project. I've got a large number of results that need to be filtered on group, project, and status. Choosing the group filters the project selection, via a roundtrip through the application, and the project selection filters the table the same way. I save the group & project in session variables so that, when the user changes pages, then clicks the main link to come back, it will remember their selection, and get them back to where they were. This all works like I intend it to.
The problem is that using the browser's back button to get back to the table from a different page will result in a duplicate wrapper (with search box, number-of-items dropdown, and pagination links) around the DataTable.
I've added the jquery-turbolinks gem.
I've tried fiddling with event listeners, but I can't make either of those ideas work.
I've tried making the body of the page exempted from Turbolinks with data-turbolinks=false
.
I've tried changing the event my script(s) key on to something other than $(document).ready()
, like page:load
. None of them prevent this.
I've tried loading all the scripts for the DataTable as exempted from Turbolinks with data-turbolinks-eval=false
in that specific page (with content_for :head
).
The only thing I've found that will prevent this wrapper duplication from happening is to simply remove the call to include the turbolinks JS from the assets entirely. And I'd have done this already if I didn't know that smarter people than me think it ought to be a part of the application. I don't know what to do. I'm looking for the elegant way to handle this.
回答1:
My table works as I expect with the following settings.
For datatable.js
or application.js
.
var dataTable = null
document.addEventListener("turbolinks:before-cache", function() {
if (dataTable !== null) {
dataTable.destroy()
dataTable = null
}
})
For view.
<table id="my-table">
..
</table>
<script>
dataTable = $('#my-table').DataTable({
stateSave: true
})
</script>
References:
- Turbolinks 5 and DataTables working together in harmony
- browser back button causes some scripts to reevaluate
来源:https://stackoverflow.com/questions/41070556/how-can-i-prevent-duplicate-wrappers-on-a-jquery-datatable-when-navigating-back