preInit firing after loading existing HTML table

preInit firing after loading existing HTML table

flusturd01flusturd01 Posts: 1Questions: 1Answers: 0
edited September 2019 in Free community support

It is my understanding of preInit that this callback is triggered before any data is loaded, "either by Ajax, or reading from the DOM". However, this does not appear to be the case. For example, I have the following table set up, along with the subsequent Javascript, and as you'll see the column render callbacks and the createdRow callback is called before the preInit is called:

Javascript

    $(document).on("preInit.dt", () => console.dir("Pre-init Called"));
    $("<table><thead><tr><th>Hello</th></thead><tbody><tr><td>Foo</td></tbody></table>").attr("id", "dt-demo-preinit").appendTo("body");
    $("#dt-demo-preinit").dataTable({
        columnDefs: [
            {targets: [0], render: (data) => { console.dir("Rendering target 0"); return data }},
        ],
        createdRow: () => console.dir("Row Created"),
    });

Results

Rendering target 0
Row Created
Pre-init Called
Rendering target 0
Rendering target 0
Rendering target 0

I just found out while making the above demo code that if the table is initially empty, then the preInit naturally is the only thing called. But if there is already HTML in the table - to be overlaid/-written by datatables via deferred ajax - then the preInit is called after the table is loaded from the DOM.

I need to be able to get to the settings object before any row is created and before any rendering is done. Is there another way to go about this aside of preInit?

Thank you.

Answers

  • colincolin Posts: 15,237Questions: 1Answers: 2,598

    Hi @flusturd01 ,

    That did surprise me, I thought the preInit would work in your case. I'll get it looked into. Out of interest, what do you need the settings object for? There may be an alternative configuration option that could be used.

    Cheers,

    Colin

  • allanallan Posts: 63,180Questions: 1Answers: 10,411 Site admin

    The reason the render is running first, is that DataTables needs to do some type detection and potential sort data collection.

    As to why the created rows are running first - its related to the fact that its is a DOM sourced table, but I don't immediately see why since this part of the code suggests otherwise and I can't remember off the top of my head why that would happen.

    However, as Colin says, what are you trying to do - there might be another way.

    Allan

This discussion has been closed.