简体   繁体   English

使用数据表启用History API

[英]Enabling History API with datatables

I have a dataTable object on a page representing a list of releases I need to keep track of with the url /releases I want to add the following functionality 我在页面上有一个dataTable对象,表示我需要跟踪的url /releases我要添加以下功能

  1. if /releases?query=<query> , the dataTable will initialized with the provided query if /releases?query=<query>dataTable将使用提供的查询进行初始化
  2. The query parameter is updated if the user changes the search term 如果用户更改搜索词,则更新query参数
  3. The back and forward buttons in the browser go the appropriate query 浏览器中的后退和前进按钮将进行相应的查询

So far I am able to do the first 2, but when I listen for the popstate event, redrawing the table triggers a pushState which I can't figure out how to prevent. 到目前为止,我能够做到前两个,但是当我监听popstate事件时,重绘表会触发一个pushState ,我无法弄清楚如何防止。 Here's my code so far: 到目前为止,这是我的代码:

$(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);          
    }
  });
});

Note, I am using a rails backend and this is inlined javascript being served in the page. 注意,我正在使用rails后端,这是在页面中提供的内联javascript。

you have only 2 options here: 这里只有2个选项:

  • move pushState code out of drawCallback. 将pushState代码移出drawCallback。 There must be some other code that causes the datatables to draw when user enters something. 必须有一些其他代码导致数据表在用户输入内容时绘制。 put your pushState code there. 把你的pushState代码放在那里。 This is the ideal solution 这是理想的解决方案
  • add a hack like this 像这样添加一个hack

     $(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; } }); }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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