DataTable() should not crash if table doesnt exist yet.

DataTable() should not crash if table doesnt exist yet.

djmdjm Posts: 20Questions: 4Answers: 0
edited September 2014 in Free community support

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

  • allanallan Posts: 61,744Questions: 1Answers: 10,111 Site admin

    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.

    since I cant specify new columns without doing so it seems?

    Correct (sadly).

    Your method looks fine.

    Allan

  • djmdjm Posts: 20Questions: 4Answers: 0
    edited October 2014

    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) ?

  • allanallan Posts: 61,744Questions: 1Answers: 10,111 Site admin
    Answer ✓

    ! table won't work as table 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 use table.context.length but context is an undocumented property at the moment...

    Allan

  • djmdjm Posts: 20Questions: 4Answers: 0

    I understand.
    Thanks very much for the clarification

This discussion has been closed.