Jquery datatable one time callback on initialize
I've been using Jquery's datatable plugin for a while and came across an issue I am not sure how to resolve in a clean manner. I want to have a function callback similar to fnCallback() which only executes when the datatable is first initalized and the first page of data has been loaded in.
I have a situation where I want to wait until my datatable has been constructed to be able to customize some of the elements (add some custom classes to elements dynamically created by the plugin).
I could do something like this:
var isInitialized = false;
$("#completed-action-items-table").dataTable(
"fnDrawCallback": function () {
if (!isInitialized) {
//do logic
isInitialized = true;
}
});
But this seems ugly.
Any suggestions would be great开发者_JAVA技巧, thanks!
I think yours may be the best technique, short of writing CSS selectors that target the elements you're interested in without adding extra classes.
The original answer works but you may prefer this more idiomatic way:
if ($.fn.dataTable.isDataTable('#example')) {
// Do something else since the dataTable's already initialized
}
else {
// Initialize the dataTable
table = $('#example').DataTable({
paging: false
});
}
Source: https://datatables.net/manual/tech-notes/3
I hope Exception Handling will work here. A simple try-catch
block will help to avoid this ReferenceError
let table = $("#table-id").DataTable({
drawCallback: function () {
try {
// Try to access the table variable here
let rowCount = table.data().rows().count();
} catch (error) {
// Do nothing in catch block: totally your wish
console.log("Table is not initialized yet")
}
},
});
精彩评论