fnStateLoadCallback/fnStateSaveCallback: add location.search

fnStateLoadCallback/fnStateSaveCallback: add location.search

av01dav01d Posts: 2Questions: 1Answers: 0

The stateSave option restores the tables state on reload. It does that by generating a localStorate/sessionStorage key based on location.pathname. In my application, I have different pages that have the same pathname, only the query-string varies.
/records.php?overview=cars vs /records.php?overview=people.
The stateSave option now restores state on both pages, while those pages are not equal.
I've changed two lines to make this work properly, I'm hoping you can incorporate these changes in a future release?

In fnStateSaveCallback, I changed
'DataTables_'+settings.sInstance+'_'+location.pathname,
to
'DataTables_'+settings.sInstance+'_'+location.pathname+'_'+location.search.replace(/\W/g,''),

In fnStateLoadCallback, I changed
'DataTables_'+settings.sInstance+'_'+location.pathname
to
'DataTables_'+settings.sInstance+'_'+location.pathname+'_'+location.search.replace(/\W/g,'')

Thanks for your consideration!

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,471Questions: 1Answers: 10,467 Site admin
    Answer ✓

    Hi,

    Thanks for your message. It should be possible to use the callback functions in the initialisation to do this rather than modifying the core library (I'm not clear if you've done that or not). I can see how this could be useful though and will consider it for future releases.

    Allan

  • av01dav01d Posts: 2Questions: 1Answers: 0

    I did indeed change this in the core library, as I hadn't noticed the stateLoadCallback and stateSaveCallback initialisation options.
    I've moved back to the "stock" core library, and added the following code to my initialisation (leaving it here for others who might need it):

    stateSaveCallback: function(settings, data) {
             localStorage.setItem(
                'DataTables_'+settings.sInstance+'_'+location.pathname+'_'+location.search.replace(/\W/g,''), // Added location.search
                JSON.stringify(data)
             );
          },
          stateLoadCallback: function(settings, callback) {
             return JSON.parse(
                localStorage.getItem('DataTables_'+settings.sInstance+'_'+location.pathname+'_'+location.search.replace(/\W/g,'')) // Added location.seatch
             );
          },
    

    This works like a charm, as far as I'm concerned, there's no need to update datatables.js.

This discussion has been closed.