在ngOnDestroy中删除全屏事件监听器

时间:2019-04-21 23:16:40

标签: javascript angular dom-events

无法在ngOnDestroy Angular 6中删除全屏更改事件监听器

我尝试在ngOnDestroy中调用.removeEventListener(),但不会删除事件。我还尝试了在10秒钟的超时后在函数中调用removeEventListeners,并且事件在此之后仍然继续被触发。

进口

import { DOCUMENT } from '@angular/common';
import { Component, HostBinding, Inject, OnInit, OnDestroy } from '@angular/core';

组件代码

elem: any;
constructor(private framesService: FramesService, private route: ActivatedRoute,
    @Inject(DOCUMENT) private document: Document) { }

 ngOnInit() {
    this.elem = this.document.documentElement;
    this.document.addEventListener('fullscreenchange', this.onFullscreenChange.bind(this));
    this.document.addEventListener('mozfullscreenchange', this.onFullscreenChange.bind(this));
 }

onFullscreenChange(event: Event) {
    event.preventDefault();
    console.log('Fullscreen event fired');
}

onViewFrame() {
    if (this.elem.requestFullscreen) { // Chrome
      this.elem.requestFullscreen();
    } else if (this.elem.mozRequestFullScreen) { // Firefox
      this.elem.mozRequestFullScreen();
    }
}

ngOnDestroy() {
    this.document.removeEventListener('fullscreenchange', this.onFullscreenChange.bind(this));
    this.document.removeEventListener('mozfullscreenchange', this.onFullscreenChange.bind(this));
}

onViewFrame()函数与页面按钮上的click事件相关联。

每次构造此组件时,都会添加事件,但永远不会删除它们。因此,如果此组件在页面上的浏览会话期间加载了3次,则每次启动全屏或使用ESC键退出全屏时,它将触发console.log 3次。希望事件在离开时被删除,以便下次可以重新正确注册。

2 个答案:

答案 0 :(得分:3)

this.onFullscreenChange.bind(this)创建对该函数的新引用。您需要将相同的引用传递给addEventListenerremoveEventListener

elem: any;
fsEventHandler: any = this.onFullscreenChange.bind(this); // <- Here

ngOnInit() {
  this.elem = this.document.documentElement;
  this.document.addEventListener('fullscreenchange', this.fsEventHandler);
  this.document.addEventListener('mozfullscreenchange', this.fsEventHandler);
}

ngOnDestroy() {
    this.document.removeEventListener('fullscreenchange', this.fsEventHandler);
    this.document.removeEventListener('mozfullscreenchange', this.fsEventHandler);
}

有关更多说明,请参见MDN

答案 1 :(得分:2)

由于您使用的是Angular,因此可以使用RxJS来实现相同的行为。

您可以使用fromEvent

创建Observable
fromEvent(this.document, 'fullscreenchange');

要触发某些功能,您需要使用.pipe()运算符添加tap,要激活它,您还需要订阅它。同时保存订阅,以便能够在ngOnDestroy()

中退订
ngOnInit() {
    this.elem = this.document.documentElement;
    console.log(this.document);
    this.fullScreen = fromEvent(this.document, 'fullscreenchange').pipe(
        tap(this.onFullscreenChange.bind(this))
      ).subscribe();
 }

onFullscreenChange(event: Event) {
    event.preventDefault();
    console.log('Fullscreen event fired');
}

ngOnDestroy() {
  this.fullScreen.unsubscribe();
}