Cleanup DataTables (all rows) when table element is removed externally
Cleanup DataTables (all rows) when table element is removed externally
Datatables 1.10.3
I have a situation where a table is being removed from the DOM by a function outside of Datatable's control. Within the table I've applied Select2 styling to drop downs, and I need to clean these up before the table is removed. I have the following function that is attempting to do this, but I'm unable to cleanup the references on rows that have been paged out of the DOM by DataTables. Assuming such functionality is available to obtain all rows in the table, regardless of their presence in the DOM, what am I doing wrong in this function since $allRows.length = 0 :
function (jqEvent, element) {
var idOfElementBeingRemovedExternally = element.id;
if ('xyz123' != idOfElementBeingRemovedExternally) {
return;
}
// Cleanup old DataTable object...
var s = $(document).dataTableSettings;
if ('undefined' != s) {
var len = s.length;
for (var i = 0; i < len; i++) {
// if already exists, remove from the array
if (s[i].sInstance == idOfElementBeingRemovedExternally) {
console.log('Externally removing DataTable element: ' + idOfElementBeingRemovedExternally);
var $dataTableInstance = s[i].oInstance;
var api = $dataTableInstance.api();
var dtTable = api.table();
var dtTableContainer = dtTable.container();
var $c2 = jQuery(dtTableContainer);
console.log('Cleaning up select2 on DT...');
$c2.find('select').each(function (index, element) {
console.log('Cleaning up Select2 on: ' + $(this).attr('id'));
$(this).select2("destroy");
});
// I thought this $() method would return me a selector on all the rows in the table, regardless of them being in the DOM
var $allRows = $dataTableInstance.$();
$allRows.find('select').each(function (index, element) {
console.log('XYZ Cleaning up Select2 on: ' + $(this).attr('id'));
$(this).select2("destroy");
});
$dataTableInstance.fnDestroy();
}
}
}
}