繁体   English   中英

使用绑定函数删除EventListener

[英]Remove EventListener with a bind function

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

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

我想停止在ngOnDestroy上监听该事件。 我尝试了这个:

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

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

我究竟做错了什么?

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

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

销毁组件时,它将自动删除

请参阅: https : //stackoverflow.com/a/41032388/9380944答案以获取更多详细信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM