问题
I am trying to implement History.js after learning to use the History API. However my popstate isn't working anymore.
What is used in the History.js as the onpopstate
? In the history API you use onpopstate
with event.state
.
What I need to know is what is used in History.js. Is it window.onstatechange
and what does it return?
回答1:
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
回答2:
The basic example says:
History.Adapter.bind(window,'statechange',function(){ // code });
And this gist (for jQuery) uses:
$(window).bind('statechange',function(){ // code });
回答3:
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.
回答4:
Try to add to your tag body the next two events:
onpopstate="(your code)"
--> for html5 browsersonhashchange="(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
.
来源:https://stackoverflow.com/questions/7986601/history-js-onpopstate