Advice on events with serverSide tables

Advice on events with serverSide tables

burbur Posts: 25Questions: 2Answers: 0
edited March 16 in Free community support

I recently noticed that when you bind the preDraw or draw events to a table after it has been initialized, these events won't fire on initialization, as in this test case. In hindsight that makes perfect sense of course, since the table is drawn before the events are bound.

However, when you do that with a table with serverSide/ajax, these events will fire on initialization, as in this test case, presumably because the ajax request takes long enough that the event binding takes place before the table is drawn.

So my question is, is this reliable with serverSide or should I refactor my scripts so that the event binding is done before the initialization of the tables?

Answers

  • kthorngrenkthorngren Posts: 21,802Questions: 26Answers: 5,043

    This test case might better illustrate the events:
    https://live.datatables.net/humirigi/2/edit

    The timing of instantiating the events is based on your requirements. You can create them in init, initComplete or ready() if you need to wait for the Datatable to be completely initialized.

    Is there a specific issue you are trying to solve?

    Kevin

  • burbur Posts: 25Questions: 2Answers: 0
    edited March 16

    Is there a specific issue you are trying to solve?

    No, my script is currently set up like in the second test case in the original post, which is working as intended, but I'm worried there might be some circumstances where the events will unexpectedly not fire on the initial page load.
    The way it's structured (I have different files that initialize tables and a common file that handles the events) it's a bit difficult to change it to work like in your test case, but I could do it if needed.
    I might merge all of it into a single file anyway, so then it would be trivial to bind the events first.

  • allanallan Posts: 64,150Questions: 1Answers: 10,584 Site admin

    With jQuery style initialisation you can listen for events prior to initialisation:

    $('#myTable')
      .on('draw', () => {})
      .DataTable();
    

    There currently isn't a way to do that with the plain JS way - you need to add the event handlers after initialisation, which can mean that you might miss some of the start up events. That is a hole in the API that I've been considering how to address.

    The initialisation with using server-side processing is async. i.e. the new DataTable() will return before the data has been loaded from the server. So adding .on('draw', () => {}) will always result in the first draw of data being called. That is part of the unit tests and won't change.

    Allan

Sign In or Register to comment.