"preDraw" event fired twice when using server-side processing

"preDraw" event fired twice when using server-side processing

halloeihalloei Posts: 23Questions: 6Answers: 0

Link to test case: https://datatables.net/examples/data_sources/server_side
Debugger code:
Execute this in the developer console:
$('#example').on('preDraw', function () { console.log('preDraw!'); });
Description of problem: When using server-side processing, "preDraw" is fired twice. The event order is as follows:
preDraw
preXhr
xhr
preDraw
draw

I did not expect the first "preDraw" and I'm struggling with it. Is that behaviour correct? I couldn't find anything regarding this.

Answers

  • colincolin Posts: 15,118Questions: 1Answers: 2,583

    This thread should help, it's asking the same thing. It's very old, back in the early days of DataTables, but the same logic still applies.

    Cheers,

    Colin

  • halloeihalloei Posts: 23Questions: 6Answers: 0

    Thanks. I understand that this happens at the very first time, when the table is initialized (one time for an empty table, one time for the data from the server). But why is the event fired twice when there's already data in the table? The only thing that happens on the first time is the display of "Processing...", but the table is not drawn.

  • colincolin Posts: 15,118Questions: 1Answers: 2,583

    Another reason is that preDraw is cancellable - so it triggers first to give the option of being able to cancel before the Ajax call is triggred,

    Colin

  • halloeihalloei Posts: 23Questions: 6Answers: 0

    Where is this useful? Wouldn't it make more sense to use preXhr to cancel an Ajax request?

  • allanallan Posts: 61,446Questions: 1Answers: 10,054 Site admin

    To be honest, I don't think it is particularly useful - it should perhaps be split out into two different events - one before the Ajax is triggered and one before the DOM is updated.

    What's the use case here?

    Allan

  • halloeihalloei Posts: 23Questions: 6Answers: 0

    An extension of mine hides an element when the user changes the search filter or the page. I use preDraw for that.
    But there's an action where the table data is updated and nothing else should change. So I'm reverting the element hiding:

    dataTable.draw();
    console.log('show');
    // show the element again
    

    But while re-writing the code for composing this answer, I realised that I have to use preXhr because of the asynchronism instead. Because there's - of course - a(nother) preDraw after "show", but no preXhr:

    preDraw
    preXhr
    show
    xhr
    preDraw
    draw

    So basically my problem is solved. But if you got an idea to improve the event system, this thread hasn't been for nothing. Thank you!

This discussion has been closed.