History.js窗口.Onstatechange不着火

History.js window.onstatechange doesn't fire

本文关键字:Onstatechange js 窗口 History      更新时间:2023-09-26

我只是一个js初学者,所以也许我只是不理解它的权利。但是当你以前用History.stateObj改变状态时,当你点击浏览器的后退/前进按钮时,window.onstatechange不应该着火吗?

我实际上看到对象改变在Firebug控制台,但window.onstatechange只是不会开火!也-非常混乱-当我使用window.onpopstate代替,对象不再改变(当使用后退/前进按钮)。

我是这样做的:

$('.container').click(function(e) {
        e.preventDefault();
        var title = $(this).data('title');
        stateObj = { show: title }
        History.pushState(stateObj, document.title, '?show=' + title);
}
window.onstatechange = function() {     
            var title = History.getState().data['show'];
            alert('title');
}

我已经从这里发现,我必须使用

History.Adapter.bind(window,'statechange',function(){
            var title = History.getState().data['show'];
            alert('title');
});

…这是有效的,但我仍然不明白为什么window.onstatechange不会开火?!

//编辑:在Github上打开一个ticket

有什么建议吗

Lucian Poston于2012年4月在GitHub上回答了这个问题:

这似乎是历史的设计。适配器事件模型。查看一下适配器的实现,例如https://github.com/balupton/history.js/blob/master/scripts/uncompressed/history.adapter.native.js

当history.js引发一个'statechange'事件时,它会调用History.Adapter.trigger(),它会迭代一系列通过之前调用History.Adapter.bind()设置的事件处理程序。Window.onstatechange()未按预期调用。

实际上,History.Adapter。Bind (window, 'statechange', function(){alert('oi');})设置窗口。onstatechange,这样如果被触发,它将调用History.Adapter。触发(window, 'statechange'),然后调用事件处理程序function(){alert('oi');}。如果你重新定义窗口。在你的例子中,它会破坏这种行为。