Very simple example with saving state for extra control

Very simple example with saving state for extra control

joshlevine102joshlevine102 Posts: 44Questions: 16Answers: 2

Hi guys. I wonder if somebody has a very simple example of adding to the saved state data to save the state of one of your own controls, such as a checkbox? I was trying to do something like this. I had my DataTable initialization in the $(document).ready()

    $(document).ready(function () {
        table = $('#sites').DataTable({
            dom: "lfrtip",
            ajax: {
              (some stuff...)
            },
            stateSave: true,

Farther down, still in the $(document).ready() I had this:

        $("#sites").DataTable().on('stateSaveParams.dt', function (e, settings, data) {
            data.featured = $("#featuredCheckbox").prop("checked");
        });
 
        $("#sites").DataTable().on('stateLoadParams.dt', function (e, settings, data) {
            $("#featuredCheckbox").prop("checked", data.featured);
        }); 

Is this anything like the right idea? I noticed, in this thread, there is an example which uses the stateSaveParams and stateLoadParams in the initialization section of the DataTable, and I wonder if this is a better way to go. Thanks.
https://datatables.net/forums/discussion/48566

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,455Questions: 1Answers: 10,465 Site admin
    Answer ✓

    The advantage of using the initialisation properties rather than the events in this case is that the order effectively sorts itself out. Using events, if you bind them after the table is initialised and the state loading is synchronous (which it is by default), then the event listener won't be added until after the state has already been loaded!

    You'd need to attach the event before the table is initialised:

    $('#sites')
      .on( 'stateLoadParams.dt', function ( ... ) {
        ...
      } )
      .DataTable( {
        ...
      } );
    

    Other than that - I don't think there is any advantage to using the callbacks or the events.

    Allan

  • joshlevine102joshlevine102 Posts: 44Questions: 16Answers: 2

    Ah thanks. This makes sense. My jQuery understanding is pretty basic.. It seems to be working quite well with the initialization properties.

This discussion has been closed.