简体   繁体   English

移除事件监听器

[英]Remove eventlistener

Help:-) How do i remove this listener?帮助:-) 我如何删除这个监听器?

this.overlay.addEventListener('click', this._handlePlay.bind(this));

_handlePlay looks like this: _handlePlay 看起来像这样:

_handlePlay() {
    this._isOpen = !this._isOpen;
  }

i tried...我试过了...

this.overlay.removeEventListener('click', this._handlePlay.bind(this));

and more desperately:更绝望的是:

this.overlay.removeEventListener('click', this._handlePlay());

but the listener wont leave the scene?但听者不会离开现场?

I have the bind as I am in js and web component context我有绑定,因为我在 js 和 web 组件上下文中

/regards /问候

The function you pass to removeEventListener needs to be the same function that you pass to addEventListener .您传递给removeEventListener的 function 需要与您传递给addEventListener的 function相同

bind creates a new function. bind创建一个新的 function。

 this.overlay.addEventListener('click', this._handlePlay.bind(this));

Since you don't keep the value of this._handlePlay.bind(this) , there's no way to get that function back to pass it to removeEventListener .由于您没有保留this._handlePlay.bind(this)的值,因此无法将 function 重新传递给removeEventListener


You need to keep the value somewhere that you can access when you later try to remove the event listener.您需要将值保存在以后尝试删除事件侦听器时可以访问的位置。

const boundHandlePlay = this._handlePlay.bind(this);
this.overlay.addEventListener('click', boundHandlePlay);
this.overlay.removeEventListener('click', boundHandlePlay);

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

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