Statechange is firing whenever i do a push-state

∥☆過路亽.° 提交于 2019-12-18 04:34:22

问题


I am using history.js to handle back button. In history.js statechange is firing whenever i do a pushstate. Why?


回答1:


According to this discussion on github, it's expected behaviour of history.js

This pull request claims to have modified history.js to be more inline with W3C Specs.




回答2:


Wanted to add, yes this is the expected behaviour of History.js. At the same time there are more discussions that critize this behaviour as it is not the W3C standard and does create some confusion.

In short, to answer your question: In the History.js pushState() function is a call to statechange at the end.

Upside of this solution is that you can just change (push) your new state and let the onstatechange()-function handle the transition. Downside is that you are not able to handle exceptions/or have to write them into the onstatechange event-handler.

I personally prefer the W3C way of handling this, as you can distinguish between back/forward button and pushState. The History.js maintainers are working on an internal flag solution, that enables you to change this behaviour:

Notice how the above calls [pushstate-calls] trigger statechange events, if for some reason you do not want this to happen then inside your statechange handler you can use the following:

if ( History.getState().internal ) { return; }

*This feature is currently in development and can only be used with the 'dev' version of History.js! Hope this will help some other people in the future :)




回答3:


After trying to accomplish this for a day now, I finally found the solution here: https://github.com/browserstate/history.js/issues/47#issuecomment-25750285

The code is pretty damn simple, the following is quoted from the link:

When you push your state

History.pushState({
    _index: History.getCurrentIndex(),
    someData: ...
}, someTitle, someUrl);

and then in the event binding

History.Adapter.bind(window, 'statechange', function () {
    var currentIndex = History.getCurrentIndex();
    var internal = (History.getState().data._index == (currentIndex - 1));
    if (!internal) {
        // your action
    }
});


来源:https://stackoverflow.com/questions/8744487/statechange-is-firing-whenever-i-do-a-push-state

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