简体   繁体   English

在类中添加/删除事件侦听器和此上下文

[英]Add / remove event listeners and this context inside a class

I am trying to conditionally add and remove event listeners on a button when the window is resized. 调整窗口大小时,我试图有条件地在按钮上添加和删除事件侦听器。 To be able to remove the event listener, it has to be a named function. 为了能够删除事件侦听器,它必须是一个命名函数。

The problem is it messes with this context, and therefore this.element in my handle() function is not accessible. 问题是它弄乱了this上下文,因此我的handle()函数中的this.element无法访问。

I can bind this and pass it along: 我可以绑定this并将其传递:

this.button.addEventListener('click', this.handle.bind(this)); 

But then it does not get removed, as it appears to not be the same event listener. 但随后它不会被删除,因为它似乎不是同一事件侦听器。 Can i pass this differently, or is there some other way to remove event listeners? 我可以通过不同的方式传递this ,还是可以通过其他方法删除事件监听器? I have tried to clone the element and replace it, but then the event listener does not get reattached. 我试图克隆元素并替换它,但是随后事件监听器没有重新连接。

As per here: How to remove all listeners in an element? 按照这里: 如何删除元素中的所有侦听器?

Here is some simplified code: 这是一些简化的代码:

export default class Classname {

  constructor(element, button) {
    this.button = button;
    this.element = document.querySelector(element);
    this.resize();
  }

  handle() {
    // do stuff
    console.log(this.element);
  }

  clickEvents() {
    if (condition) {
      this.button.addEventListener('click', this.handle);
    } else {
      this.button.removeEventListener('click', this.handle);
    }
  }

  resize() {
    window.addEventListener('resize', () => {
      this.clickEvents();
    })
  }
}

You can assign the bound handler to a property of the instance, and then pass that bound handler to both addEventListener and, later, removeEventListener : 您可以将绑定处理程序分配给实例的属性,然后将该绑定处理程序传递给addEventListener以及以后的removeEventListener

clickEvents() {
  if (condition) {
    this.boundHandler = this.handle.bind(this);
    this.button.addEventListener('click', this.boundHandle);
  } else {
    this.button.removeEventListener('click', this.boundHandle);
  }
}

Another possibility would be to bind in the constructor instead: 另一种可能性是绑定在构造函数中:

constructor(element, button) {
  this.boundHandler = this.handle.bind(this);
  this.button = button;
  this.element = document.querySelector(element);
  this.resize();
}

You can convert the handle method to an arrow function and then the this will be retained. 您可以将转换handle的方法来箭头功能,那么this将被保留。

  handle = () => {
    // do stuff
    console.log(this.element);
  }

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

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