[英]Removing beforeunload event in angular
我正在嘗試使用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);
}
它仍然會發出警報消息。 我在這里錯過了什么嗎? 我嘗試使用和不使用最后一個參數。 似乎沒有任何事情在這里起作用。
addEventListener
和removeEventListener
在 JavaScript 中以一種奇怪的方式實現,它們需要完全相同的參數才能檢索注冊的偵聽器。 這與返回 id 的setTimeout
不同。
在 Angular 中,通常我會這樣做:
private readonly 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;
}
該標志將阻止偵聽器注冊兩次
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.