how to catch a state change event ONCE with history.js?

若如初见. 提交于 2019-12-05 09:15:06

It's because you're calling the pushState function when you load the page, which also causes a statechange. I was in a similar situation and used a but a boolean before my pushStates so I knew I was doing a pushState. It looks like this...

historyBool = true;
History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate

var State = History.getState(); // Note: We are using History.getState() instead of event.state

    //don't run our function when we do a pushState
    if(historyBool){
        historyBool = false;
        tempFunction = new Function(State.data.ajaxRunFunction);
        tempFunction();
    }
    historyBool = true;
});

historyBool = false;
historySet = {ajaxRunFunction: "upc('" + pageID + "','')"};
History.pushState(historySet,"","");

While not relevant to your specific problem, I had a scenario where I needed to unbind the event handler from the History Adapter. To do so you can unbind the "statechange" event from window, which is what History.Adapter binds to when you call History.Adapter.bind() :

$(window).unbind('statechange.namespace');

You can added a namespace to the event to avoid unbinding other unrelated event handlers as above, or use a named function to unbind that function specifically. To use the above namespace, you would need to bind the handler using the same namespace, ie

History.Adapter.bind(window,'statechange.namespace',function(){...}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!