gpt4 book ai didi

javascript - 删除或销毁事件监听器

转载 作者:太空狗 更新时间:2023-10-29 18:16:49 26 4
gpt4 key购买 nike

致力于 angular2 应用程序。我有 RxJS 计时器 实例,它会在用户登录时向用户推送通知。但它不应推送通知如果选项卡未处于事件状态,则调度程序应暂停/停止。也完成了。

但最主要的是我已经将 window (focus, blur ) 事件监听器添加到 ngOnInit()。当我们更改页面/组件时,我试图在 ngOnDestroy() 上销毁它,但它也不会停止。当我们回到同一页面时,该监听器的第二个实例也启动了,现在我的内存/范围内将有 2 个调度程序实例。

所以任何人都知道如何在 ngOnDestroy 或任何其他地方删除/销毁 window.listener !

代码:

timerFlag: boolean = true;
private timer;
private sub: Subscription;

ngOnInit() {
this.sub = null;
this.timer = null;
console.log("home-init");
window.addEventListener('blur', this.disableTimer.bind(this), false);
window.addEventListener('focus', this.initializeTimer.bind(this), false);
}
disableTimer() {
if (this.sub !== undefined && this.sub != null) {
this.sub.unsubscribe();
this.timer = null;
}
}
initializeTimer() {
if (this.timerFlag) {
if (this.timer == null) {
this.timer = Observable.timer(2000, 5000);
this.sub = this.timer.subscribe(t => this.runMe());
}
}
}
runMe() {
console.log("notification called : " + new Date());
}
ngOnDestroy() {
console.log("Destroy timer");
this.sub.unsubscribe();
this.timer = null;
this.sub = undefined;
this.timerFlag = false;
window.removeEventListener('blur', this.disableTimer.bind(this), false);
window.removeEventListener('focus', this.initializeTimer.bind(this), false);
}

任何人都可以指导我如何销毁事件监听器实例,以便下次我来到同一页面时不会启动第二个实例。

window listener 开始之前,我也尝试在 ngOnInit 中删除监听器。

最佳答案

1) 我想这应该可行:

ngOnInit() {
window.addEventListener('blur', this.disableTimer, false);
window.addEventListener('focus', this.initializeTimer, false);
}

disableTimer = () => { // arrow function
...
}
initializeTimer = () => { // arrow function
...
}

ngOnDestroy() {
window.removeEventListener('blur', this.disableTimer, false);
window.removeEventListener('focus', this.initializeTimer, false);
}

Plunker Example

2) 另一种方法是将您的监听器存储在变量中,因为 .bind 每次都会返回新函数

disableTimerFn: EventListenerOrEventListenerObject;

ngOnInit() {
this.disableTimerFn = this.disableTimer.bind(this);
window.addEventListener('blur', this.disableTimerFn, false);
}

ngOnDestroy() {
window.removeEventListener('blur', this.disableTimerFn, false);
}

Plunker Example

3) 但也许最好的方法是使用 angular2 方式:

@HostListener('window:blur', ['$event'])
disableTimer (event) { ... }

组件销毁时自动移除

Plunker Example

4) 另一种 angular2 方法是使用 Renderer

globalListenFunc: Function;
constructor(private renderer: Renderer) { }
ngOnInit() {
this.globalListenFunc = this.renderer.listenGlobal('window', 'click', this.onClick.bind(this))
}

onClick() {
alert('click');
}

ngOnDestroy() {
this.globalListenFunc(); // destroy listener
}

Plunker Example

另见

关于javascript - 删除或销毁事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41031961/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com