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

问题描述 投票:0回答:2

无法在ngOnDestroy Angular 6中删除fullscreenchange事件侦听器

我试过在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()函数与页面上按钮的单击事件相关联。

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

javascript angular dom-events
2个回答
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


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();
}
© www.soinside.com 2019 - 2024. All rights reserved.