[英]Removing beforeunload event in angular
I am trying to remove event using window.removeEventListener
which I have added using window.addEventListener
for event beforeunload
but it is not getting removed.我正在尝试使用window.removeEventListener
删除事件,我已经使用window.addEventListener
添加了事件beforeunload
但它没有被删除。 I am trying following code我正在尝试以下代码
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);
}
It is being added but when I am trying to remove the same function using below code :它正在添加,但是当我尝试使用以下代码删除相同的功能时:
removeAlertWithListener() {
window.removeEventListener('beforeunload', null,true);
}
It still gives alert message.它仍然会发出警报消息。 Am I missing something over here?我在这里错过了什么吗? I tried with and without last param.我尝试使用和不使用最后一个参数。 None of the thing seems working here.似乎没有任何事情在这里起作用。
addEventListener
and removeEventListener
are implemented in a weird way in JavaScript, they need exactly the same parameters in order to retrieve the registered listeners. addEventListener
和removeEventListener
在 JavaScript 中以一种奇怪的方式实现,它们需要完全相同的参数才能检索注册的侦听器。 That's different from, like, setTimeout
where an id is returned.这与返回 id 的setTimeout
不同。
In Angular, usually I do something like this:在 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;
}
The flag will prevent the listener to be registered twice该标志将阻止侦听器注册两次
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.