删除或销毁事件侦听器

时间:2016-12-08 04:46:56

标签: javascript angular addeventlistener event-listener

处理 angular2 应用程序。我有 RxJS计时器实例,当用户登录时会将通知推送给用户。但如果标签未处于活动状态,那么它不应该推送通知然后调度程序应暂停/停止。它也完成了。

但主要的是我已将窗口(焦点,模糊)事件监听器添加到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 中的监听器。

1 个答案:

答案 0 :(得分:5)

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

另见

相关问题