DataTable() should not crash if table doesnt exist yet.
DataTable() should not crash if table doesnt exist yet.
http://jsfiddle.net/b8xn0j12/4/
Hello.
(1) It seems calling $(ParElem).DataTable()
returns the table created at "ParElem" if its been created already but will crash if it hasnt.
One could work around this by something like:
function tableForElem(ParElem)
{
var hasExistingTable = ($(ParElem).children().length > 0);
return hasExistingTable ? $(ParElem).DataTable() : null;
}
but it would be nice if DataTable() did this itself.
(2) Secondly, (and the reason why im querying if a DataTable has been created already), if I want to re-create a DataTable (since I cant specify new columns without doing so it seems?) is this the best way to do it:
if(OldTable) // free the old table .. (2) is this the best way?
{
//OldTable.clear();
OldTable.destroy();
$("#example").empty(); // use fnClearTable instead?
}
Many thanks in Advance
This question has an accepted answers - jump to answer
Answers
I don't understand what you mean by "crashes"? If you try to run
$().DataTable()
on an element that jQuery can't match it simply does nothing - example. That is a function of all jQuery plug-ins, not DataTables.Correct (sadly).
Your method looks fine.
Allan
I must have been mistaken about the "crash" .. sorry.
What i mean is
```var table = $('#doesntExist_zwtqzqwt').DataTable();
if(!table)
console.log("no table .... create one");
else
console.log("table....skip creation");```
prints "table....skip creation" // which is not what Id expect.
What test can I use instead of
if(!table)
?! table
won't work astable
is an API instance, in exactly the same way as! $('#doesntExist')
won't work because it is a jQuery instance.What you can do is use
! table.tables().nodes().length
to check if there are any tables. Its a bit clunky - you could usetable.context.length
butcontext
is an undocumented property at the moment...Allan
I understand.
Thanks very much for the clarification