Using Data Table along with Turbolinks

1 Min. Read
Sep 18, 2020

Setting up Data Table in Rails

There are two easy ways you can use Data Tables in your application.

One is by installing data table gem in your rails project. You can find more information in the official github link for the gem: (https://github.com/rweng/jquery-datatables-rails)

The other method(the one that I used), is by including jQuery’s Data Table plugin. You can get all the related CDN’s and CSS files from this link: (https://datatables.net/)

Usage of datatable with turbolinks

Turbolinks

Firstly, let us know what turbolinks is, and how it works. Turbolinks is a JavaScript library that eliminates full page reloads. When you use the back or forward button, or follow a link from the web page, turbolinks uses JS to fetch server-rendered HTML. And then the fetched content is put into the DOM without having to reload the page.

Usage of DataTable with Turblolinks

1
2
3
document.addEventListener('turbolinks:load', function () {
   $('#example-table').DataTable();
});

Using DataTable With Turbolinks is as simple as that.

Duplication Of Data Table

As seen in the Usage of DataTable with Turblolinks section, our web page initilaizes DataTable to our example-table everytime our DOM is completed rendered by Turbolinks.

This causes the $('#example-table').DataTable() to execute everytime our page is rendered using turbolinks. Now, when you return to a cached page using turbolinks, you can see the example-table having DataTable initialized for it twice, and hence causing the duplication effect of the DataTable.

How I tackled the problem

As, explain earlier the piece of code $('#example-table').DataTable() initializes DataTable for our table each time it is called.

So, by assigning the $('#example-table').DataTable() to a variable, and then checking whether the variable has already been initialized or not before turbolinks loads our DOM, and clearing the Data Table if the variable has been already initialized, we can solve the duplication problem.

The Sample Code is given below:

1
2
3
4
5
6
7
8
9
10
11
12
let dataTable = ""

document.addEventListener("turbolinks:before-cache", function () {
  if (dataTable !== null) {
      dataTable.destroy();
      dataTable = null;
  }
});

document.addEventListener('turbolinks:load', function () {
  dataTable = $('#example-table').DataTable();
});