Enabling History API Using Data

I have a dataTable object on a page representing a list of releases that I need to track with url /releases I want to add the following functionality

  • if /releases?query=<query> , dataTable will be initialized with the provided query
  • The query parameter is updated if the user changes the search query.
  • The back and forward buttons in the browser go to the corresponding request

So far I could do the first 2, but when I listen to the popstate event, redrawing the table causes pushState , which I cannot figure out how to prevent. Here is my code:

 $(document).ready(function(){ var prevSearch; var table = $('#releases').dataTable({ "bJQueryUI" : true, "sPaginationType" : "full_numbers", "iDisplayLength" : 50, "oSearch": {"sSearch": '#{params[:query]}'}, "fnDrawCallback": function(oSettings) { var curSearch = oSettings.oPreviousSearch.sSearch; if (!prevSearch) { prevSearch = curSearch; } else if (curSearch != prevSearch) { console.log("changed to: " + curSearch); history.pushState({query: curSearch}, "title", "releases?query=" + curSearch); prevSearch = curSearch; } } }); window.addEventListener("popstate", function(e) { if (e.state) { table.fnFilter(e.state.query); } }); }); 

Please note that I am using the rails backend and this is the built-in javascript that will be displayed on the page.

+4
source share
1 answer

you have only 2 options:

  • move pushState code from drawCallback. There must be some other code that causes data to be drawn when the user enters something. put your PushState code there. This is the perfect solution.
  • add hack like this

     $(document).ready(function () { var prevSearch; var saveState = true; var table = $('#releases').dataTable({ "bJQueryUI":true, "sPaginationType":"full_numbers", "iDisplayLength":50, "oSearch":{"sSearch":'#{params[:query]}'}, "fnDrawCallback":function (oSettings) { var curSearch = oSettings.oPreviousSearch.sSearch; if (!prevSearch) { prevSearch = curSearch; } else if (curSearch != prevSearch) { console.log("changed to: " + curSearch); if (saveState) { history.pushState({query:curSearch}, "title", "releases?query=" + curSearch); } prevSearch = curSearch; } } }); window.addEventListener("popstate", function (e) { if (e.state) { saveState = false; table.fnFilter(e.state.query); saveState = true; } }); }); 
+2
source

Source: https://habr.com/ru/post/1445671/


All Articles