Keyur Keyur - 5 months ago 34
Javascript Question

How to pass custom arguments to dataTables footerCallback

I want to add a custom argument to

footerCallback
in jQuery dataTables.

This is some part of my code :

oTableClient = $('#tbl_client').DataTable({
"footerCallback": function(){
dataTableFooterCallback('client');
}
});
function dataTableFooterCallback(type, row, data, start, end, display) {
var api = this.api(), data;

if (type == 'client') {
data = api.column(6, {page: 'current'}).data();
} else {
data = api.column(5, {page: 'current'}).data();
}
}


But getting an error,


TypeError: this.api is not a function

var api = this.api(), data;


Where am I wrong?

Answer

You are trying to access the dataTable API on this where it not exists. Every dataTable method or callback returns either an API or the API accessible through the this context, but you have to pass it yourself if you want to operate on this.api() in your own function. You can do that by calling the dataTableFooterCallback() with apply() :

footerCallback: function() {
  dataTableFooterCallback.apply(this, arguments)
}

Now you have passed this to dataTableFooterCallback and have access to the API :

function dataTableFooterCallback(type, row, data, start, end, display) {
  //get first row trough the API
  console.log(this.api().row(0).data())
  //rest of passed arguments same as footerCallback()
  console.log(arguments)
}

demo -> http://jsfiddle.net/95h3a8nw/


Adding extra variables to arguments is a little bit tricky since arguments not is a real array, it does not have prototype methods such as push(). This workaround will work :

footerCallback: function() {
  var newArguments = Array.prototype.slice.call(arguments)
  newArguments.push('client')
  dataTableFooterCallback.apply(this, newArguments)
}

In dataTableFooterCallback() 'client' is now added as last param in the function call. See updated fiddle -> http://jsfiddle.net/95h3a8nw/1/