History.js onpopstate?

我是研究僧i 提交于 2019-12-03 21:21:47
benck

You can't tell it's from push or pop. This is by its design. You should not do anything before push event. Instead, you should pass all your required data to the first parameter.

History.pushState(data,title,url)

Then retrieve data from onstatechange and do some actions.

Check this: https://github.com/browserstate/history.js/issues/47

The basic example says:

History.Adapter.bind(window,'statechange',function(){ // code });

And this gist (for jQuery) uses:

$(window).bind('statechange',function(){ // code });

You're supposed to use the event window.statechange, which has been invented by History.js as window.popstate is too general. You react to it by binding an event handler to it, typically like so:

History.Adapter.bind(window, 'statechange', function () {
    var state = History.getState();
    // Your code goes here
});

Or you could use a router abstraction, which should be easier. I wrote one for example, called StateRouter.js. Some simple example code:

var router = new staterouter.Router();
// Configure routes
router
  .route('/', getHome)
  .route('/persons', getPersons)
  .route('/persons/:id', getPerson);
// Perform routing of the current state
router.perform();
// Navigate to the page of person 1
router.navigate('/persons/1');

I also have a fiddle for demonstration purposes.

Try to add to your tag body the next two events:

  1. onpopstate="(your code)" --> for html5 browsers
  2. onhashchange="(your code)" --> for html4 browsers

If you have any trouble like twice run your code, try build a function that asks if pushState is ready and use onpopstate. If not, in the other case, use onhashchange.

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