Does jquery.empty() / html(newContent) remove DataTable from memory?

Does jquery.empty() / html(newContent) remove DataTable from memory?

isepiseisepise Posts: 14Questions: 4Answers: 1
edited May 2017 in Free community support

I load views dynamically into divs using ajax calls.
The views sometimes contain DataTables, that initialize after the view is loaded.
Fill new view into target div: $("#targetDiv").html(newContent)
Inside view - the DataTable is initialized in the $(document).ready(function () {}) Handler.

Question:
I simply replace the divs content with new content using jquery html().
Jquery removes all old dom elements and event handler ---> Is the DataTable instance also removed?
In other words. When i remove the dom element (a table) --> Is the corresponding DataTable instance removed, too?
Or should i expect memory issues?

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 61,732Questions: 1Answers: 10,110 Site admin
    Answer ✓

    Jquery removes all old dom elements and event handler ---> Is the DataTable instance also removed?

    No! Use destroy() to kill the DataTable first which will unbind any event listeners and clear the memory it uses. It will also fire an event that let's any plug-ins being used know to clean up their memory use as well. With that done it is then safe to remove the table from the DOM (although destroy() has an option to do that for you).

    You will have memory leaks a plenty if the table node is just removed :smile:.

    Allan

  • isepiseisepise Posts: 14Questions: 4Answers: 1

    Thank you for your answer.
    The problem is - the view dont know where he is rendered into. And - the view dont gets an event "you are replaced right now - please dispose your resources".
    So.. at the moment i have no location, where i can put the "destroy" call.

  • sureshkondurusureshkonduru Posts: 3Questions: 1Answers: 0

    Datatable.destroy(); helps you to clear the datatable binded data.

  • isepiseisepise Posts: 14Questions: 4Answers: 1

    I could scan the content which is to be replaced/removed for html table elements.
    Then use the $.fn.DataTable.isDataTable() function to find out, if it is a DataTable. If yes.. call the destroy function.

  • allanallan Posts: 61,732Questions: 1Answers: 10,110 Site admin

    $.fn.dataTable.tables() can be used to get all the DataTables on the page.

    Allan

  • isepiseisepise Posts: 14Questions: 4Answers: 1

    Note:
    I use a cleanup function now. Before i fill in new html content with $(selector).html(newContent)

    //Cleanup Datatable Instances
    $(selector).find("table").each(function (idx, table) {
      if ($.fn.DataTable.isDataTable(table)) {           
        $(table).DataTable().destroy();
      }
    });
    
This discussion has been closed.