angular中事件监听后this传导问题

214

原本的写法:

window.addEventListener("deviceorientation", this.watch);
window.removeEventListener("deviceorientation", this.watch);

这样在this.watch中无法调用正确的this对象

通过this.watch.bind(this);传递了this后,removeEventListener又失效了。

后查得,可以使用Renderer2提供的listen方法:

import { Renderer2 } from '@angular/core';

  constructor(
    private renderer: Renderer2,
  ) {}

  start() {
    this.listenFunc = this.renderer.listen("window", "deviceorientation", (e) => {
      console.log(e.alpha, e.beta, e.gamma);
    });
  }

  stop() {
    this.listenFunc();
  }

调用返回函数listenFunc,即可取消监听。

留下一个答复

Please enter your comment!
Please enter your name here