简体   繁体   中英

Jquery-DataTables catch search event but not those from ordering

I am rendering a graph of the data in the Jquery DataTables table and would like to trigger a function to re-draw the graph upon a change in the table contents from the UI search OR calling a search such as below

$('#mytable').DataTable().column(0).search('my value').draw()

on my table I have the following code

var table = $('#mytable').DataTable({
    //my settings here
}).on( 'search.dt',   function () { updateGraph( GraphData ) ; } );

The code is working but on a sort event, such as ordering a column a search followed by an order event is triggered. Is there a way to trigger a change only when the table contents change?

see this example for further information.https://datatables.net/examples/advanced_init/dt_events.html

That was a good catch! Never realized that the search.dt event was triggered even on simple ordering. A peculiar issue actually. Perhaps other people will come up with a better idea, but I think keeping a "snapshot" of the current rows and compare them to the rows when search.dt is triggered could solve the problem. If the snapshot is based on the table rows default order, or index , not by the applied ordering, then we could trigger a datachange.dt event if and only if data actually has changed within the dataTable :

var table = $('#example').DataTable({
   snapshot: null
})
.on('search.dt', function() {
  var snapshot = table
     .rows({ search: 'applied', order: 'index'})
     .data()
     .toArray()
     .toString();

  var currentSnapshot = table.settings().init().snapshot;

  if (currentSnapshot != snapshot) {
   table.settings().init().snapshot = snapshot;
   if (currentSnapshot != null) $('#example').trigger('datachange.dt')
  }
})
.on('datachange.dt', function() {
  alert('data has changed')
  //updateGraph( GraphData )
})

demo -> http://jsfiddle.net/hftuew5u/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM