删除或销毁事件监听器

Remove or destroy event listener

正在开发 angular2 应用程序。我有 RxJS 计时器 实例,它会在用户登录时向用户推送通知。但是它不应该推送通知 如果选项卡未激活,那么调度程序应该 pause/stop 。也搞定了。

但最主要的是我添加了 window(焦点,模糊)事件侦听器到 ngOnInit()。当我们更改 page/component 时,我试图在 ngOnDestroy() 上销毁它,但它也不会停止。当我们回到同一页面时,该侦听器的第二个实例也启动了,现在我的 memory/scope.

中将有 2 个调度程序实例

所以任何人都知道如何在 ngOnDestroy 或任何其他地方 remove/destroy 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 监听器 .

开始之前

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 returns 每次都有新功能

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

另见