javascript - 使用绑定(bind)函数删除 EventListener

标签 javascript angular ionic-framework

我正在监听这样的 deviceorientationabsolute 事件(在 ngOnInit 上):

 this.deviceOrientationEvent = this.onDeviceOrientation.bind(this);
 window.addEventListener("deviceorientationabsolute", this.deviceOrientationEvent);

我想停止监听 ngOnDestroy 上的该事件。我试过这个:

window.removeEventListener("deviceorientationabsolute", this.deviceOrientationEvent);

但我仍然可以在控制台中看到它正在监听该事件。

我做错了什么?

最佳答案

您可以使用 @HostListener 来处理它,而不是通过 window.addEventListener 方法进行处理,如下所示

@HostListener('window:deviceorientationabsolute', ['$event'])
deviceOrientationAbsoluteEvent(event) { ... }

组件销毁时会自动移除

引用:https://stackoverflow.com/a/41032388/9380944回答以获取更多详细信息。

关于javascript - 使用绑定(bind)函数删除 EventListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57541864/

相关文章:

javascript - 在 jquery 中访问 angular2 变量

android - 任务 ‘:mergeDebugResources’ ionic 2 执行失败

android - Ionic Android 支持的最低 Gradle 版本是 4.6。当前版本是4.1

ionic-framework - @IonicPage 装饰器是否已弃用?

javascript - XPath .evaluate() 不返回任何内容

javascript - 使用 JavaScript 解析 <title> 标签中的内容

javascript - datepicker 禁用 future 日期并将今天日期显示为默认日期

javascript - 在 Prototype.js 中获取元素的外部宽度

Angular 不显示 Font Awesome 图标

Angular - HostListener 指令和传递值