Search code examples
javascriptjqueryecmascript-6datatablesarrow-functions

DataTables, es6 arrow functions and this


I have the following datatables initialisation in which I use the preDrawCallback function to hide and show pagination and filters based on the number of records in the table.

As it is part of a webpack project, I have turned it into es6 but I have had to disable the object shorthand for the function as I am unable to find a way of getting the current table without using this:

$tables.DataTable({
  preDrawCallback: function(settings) { // eslint-disable-line object-shorthand

    const $table = $(this); // is there a way to get this table without using this?
    
    // rest of code
  }
})

Having looked through a lot of documentation, there doesn't seem to be an argument they pass into the function where I can get that table and all the examples use $(this).

My question is do I have to use this or is there some other way of getting the table so I can change the named function into an arrow function?

Update

Seems that I was looking at the wrong problem and didn't need to use arrow functions after all and fixing the lint error solved the need to not use this (see answer below), but just in case anyone doesn't want to use this, after a lot of console logging of different things, I found the current table id is held in the settings that is passed in so you can do

$(`#${settings.sTableId}`).DataTable();

Solution

  • If, as you say, the value isn't passed in as a parameter, then you'll need to use a normal function. Normal functions and arrow functions have different behaviors for this, so you'll need to pick the right tool for the job.

    As for that lint error you're seeing, that doesn't have anything to do with arrow functions. It's just telling you to write it like this:

    $tables.DataTable({
      preDrawCallback(settings) { // <-- using shorthand on this line
        const $table = $(this); 
    
        // rest of code
      }
    });