{hero}

on

Since: DataTables 2.3

Add event listeners to the DataTable during initialisation.

Description

DataTables has an extensive collection of events that you can listen for using the on() method. It can also be useful to listen for events that occur during the DataTable's initialisation so you can take actions as needed (e.g. using preXhr to know when an Ajax request is made). This property provides that ability.

Any event name that is given in the list of events can be used as the object property name, while the value may take a callback function as the event handler, or an array of functions if you wish to listen with more than one event handler.

The arguments passed to the event handlers are identical to those for the event identified by the property name.

Type

This option can be given in the following type(s):

Default

null

Examples

Listen for the draw event:

new DataTable('#example', {
	on: {
		draw: () => {
			console.log('Draw event');
		}
	}
});

Using the preXhr event to add data to the request:

new DataTable('#example', {
	ajax: '/api/data',
	on: {
		preXhr: (e, s, data) => {
			data.extra = 1;
		}
	}
});

Listen for multiple events:

new DataTable('#example', {
	on: {
		order: () => {
			console.log('Order event');
		},
		search: () => {
			console.log('Search event');
		}
	}
});

Array of events:

new DataTable('#example', {
	on: {
		draw: [
			() => {
				// Listener 1
			},
			() => {
				// Listener 2
			}
		]
	}
});

Related

The following options are directly related and may also be useful in your application development.