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.
source share