当我点击后退或前进按钮并且 popstate 事件触发时,我可以获得前一个状态的状态对象吗?因为不是 e.state 提供的状态对象,而是我刚刚后退/转发的状态对象?
或者,我可以检测按下的是后退按钮还是前进按钮?
我需要这个,因为我有多个子系统,它们都需要同时使用 js 历史记录,当然,我可以在推送时保存所有子系统的状态,但是,当我弹出时,我必须将状态恢复到所有子系统这也是不需要的,因为它重置了我不需要的对象。例如
state 1 = {a:1, b:1, c:1}
push a = 2
state 2 = {a:2, b:1, c:1}
hit back button, popstate fires state 1 to me
restart a with 1, b with 1, c with 1 while I only need to restart a
另类幻想解决方案
....
hit back button, popstate fires state 1 to me
I also get state 2 (the one I just moved away from) through some black magic
do a differential comparison between the 2 states, find out that I only need to modify a
restart a with 1
编辑:哦,还要澄清一下,没有简单的方法可以检查页面上当前的状态 a、b 和 c (因为它比 abc 和 123 更复杂一些)
答案是装饰pushState
记录应用程序中的当前状态。所以,像这样:
var app = {
currentState: false,
originalPushState: false,
pushState : function(state, title, href) {
app.currentState = state;
app.originalPushState.call(history, state, title, href);
},
onPopstate : function(event) {
var newState = event.state;
var oldState = app.currentState;
app.currentState = newState;
// you now have the current state and the state you came from
},
init : function() {
window.onpopstate = app.onPopstate;
app.originalPushState = history.pushState;
history.pushState = app.pushState;
}
}
app.init();
作为旁白,popstate
相当混乱。当您弹出常规数组时,您会得到弹出的值,而不是现在位于其末尾的值,因此从语义上讲,它有点奇怪。此外,history.state
总是包含当前状态,所以event.state
是多余的。我想说,设计师的奇怪选择,如果有的话更明智event.popped
是指向实际弹出的页面状态的指针(可能仅当它与您的站点位于同一域中时才可用)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)