【发布时间】:2017-04-23 06:03:29
【问题描述】:
正在开发 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);
}
谁能指导我如何销毁事件侦听器实例,以便下次访问同一页面时不会启动第二个实例。
我已经尝试在 ngOnInit 中删除监听器,以及在 window listener 开始之前。
【问题讨论】:
-
被移除的监听器必须与添加的监听器相同(在
===意义上)。this.disabletimer.bind(this)在您调用两次时不相同。顺便说一句,这与 Angular 无关。这是一个纯粹的 JS 问题。 -
那么,无论如何我可以删除监听器!
-
是的,正如重复的问题所暗示的那样,将侦听器存储在一个变量中,然后使用该变量将其删除。
-
作为下面的答案,对吧?
标签: javascript angular addeventlistener event-listener