我正在嘗試洗掉使用事件window.removeEventListener添加window.addEventListener的事件beforeunload,但它沒有被洗掉。我正在嘗試以下代碼
addAlertWithListener(){
window.addEventListener('beforeunload', (event) => {
// Cancel the event as stated by the standard.
event.preventDefault();
// Chrome requires returnValue to be set.
event.returnValue = 'You are currently in edit mode. Are you sure you want to refresh the page?';
},true);
}
它正在添加,但是當我嘗試使用以下代碼洗掉相同的功能時:
removeAlertWithListener() {
window.removeEventListener('beforeunload', null,true);
}
它仍然會發出警報訊息。我在這里錯過了什么嗎?我嘗試使用和不使用最后一個引數。似乎沒有任何事情在這里起作用。
uj5u.com熱心網友回復:
addEventListener并且removeEventListener在 JavaScript 中以一種奇怪的方式實作,它們需要完全相同的引數才能檢索注冊的偵聽器。這與setTimeout回傳 id 的地方不同。
在 Angular 中,通常我會這樣做:
private BEFORE_UNLOAD_PARAMS = ['beforeunload', (event) => ..., true];
private isBeforeUnloadActive: boolean = false;
addAlertWithListener() {
if (this.isBeforeUnloadActive) return;
window.addEventListener(...this.BEFORE_UNLOAD_PARAMS);
this.isBeforeUnloadActive = true;
}
removeAlertWithListener() {
window.removeEventListener(...this.BEFORE_UNLOAD_PARAMS);
this.isBeforeUnloadActive = false;
}
該標志將阻止偵聽器注冊兩次
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/476266.html
標籤:javascript 有角度的 卸载前
上一篇:點擊“提交”按鈕(帶有選擇和數字選項)后,我需要添加一個警報(或類似的彈出視窗)
下一篇:在js陣列中查找缺失的月份
