自定義事件
如果我們想在window上面掛載一個自定義事件該如何實現呢?比如:
window.addEventListener("testEvent",(e)=>{
console.log(e.data);
})
想實現上面的事件監聽可以利用window.dispatchEvent這個API派發自定義事件.整個過程是先創建自定義事件,再通過window.dispatchEvent派發事件,最後在window.addEventListener中監聽事件,代碼如下:
<body>
<button onclick="trigger()">觸發</button>
</body>
<script>
function bindEvent(type){
return (data)=>{
const e = new Event(type);
e.data = data;;
window.dispatchEvent(e);
}
}
function trigger(){
let event_trigger = bindEvent("testEvent");
event_trigger(1);
}
window.addEventListener("testEvent",(e)=>{
console.log(e.data);
})
</script>
點擊按鈕:
實際應用
如何在實際場景中應用此特性呢?瀏覽器有很多事件是沒有監聽函數的比如history.pushState,history.replaceState等.在某些應用場景下希望通過調用history.pushState跳轉後也能有回調函數監聽.此時我們就可以利用上面講述的自定義事件實現此需求.
<body>
<button onclick="trigger()">觸發</button>
</body>
<script>
function trigger(){
history.pushState(JSON.stringify({id:1}),"首頁","/list");
}
window.addEventListener("pushState",(e)=>{
console.log("您跳轉了,帶過來的參數爲:"+e.data);
})
window.onload = function(){
bindEvent("pushState");
}
function bindEvent(type){
const fn = history[type];
history[type] = function(...args){
fn.call(history,...args);
const e = new Event(type);
e.data = args[0];
window.dispatchEvent(e);
}
}
</script>
運行結果: