
1.4.3 手动触发事件
对于popstate事件,如果调用history.pushState方法,则history.replaceState方法不会被触发,仅在移动栈指针时才会触发popstate事件。对于开发者来说,这缺少一定的控制;不过通过dispatchEvent方法,也能实现不移动栈指针便可控制popstate事件的触发。调用dispatchEvent方法时,dispatchEvent方法返回值为事件的取消状态,其签名为

其接收一个事件实例作为入参,event是要被派发的事件对象。target被用来初始化事件和决定将会触发的目标。当该事件是可取消的(cancelable为true)且至少一个该事件的事件处理方法调用了event.preventDefault时,调用dispatchEvent的返回值为false;否则返回true。
对于如window.addEventListener('popstate',handlePopState)监听的popstate事件,则可在不移动栈指针的情况下调用window.dispatchEvent手动触发。

event事件通过实例化PopStateEvent对象得到,并传入事件的type为popstate:


对于IE浏览器,PopStateEvent的类型为object,不能通过new实例化得到对应的event实例。event实例可通过createEvent创建,事件类型可通过initEvent设置。initEvent支持3个参数:

这3个参数分别表示事件名称、是否可以冒泡、是否阻止事件的默认操作。在IE浏览器中,popstate事件的触发方式为

在IE浏览器中,Event类型为对象,而其他浏览器如Chrome,Event类型为函数,可兼容写法如下:

同理,对于hashchange事件,也可实现对应的手动触发方式:


对于手动触发的hashchange事件,其不受当前hash的影响。我们在1.3节中介绍过,前后两次设置相同的location.hash值不会触发hashchange事件,但对于手动触发的方式来说,其可反复触发hashchange事件。

此方法即使不移动栈指针,也会触发hashchange事件,这在某些特定场景中会有具体应用。