当前位置: 代码迷 >> JavaScript >> 在类中添加/删除事件侦听器和此上下文
  详细解决方案

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

热度:50   发布时间:2023-06-05 15:49:50.0

调整窗口大小时,我试图有条件地在按钮上添加和删除事件侦听器。 为了能够删除事件侦听器,它必须是一个命名函数。

问题是它弄乱了this上下文,因此我的handle()函数中的this.element无法访问。

我可以绑定this并将其传递:

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

但随后它不会被删除,因为它似乎不是同一事件侦听器。 我可以通过不同的方式传递this ,还是可以通过其他方法删除事件监听器? 我试图克隆元素并替换它,但是随后事件监听器没有重新连接。

按照这里:

这是一些简化的代码:

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();
    })
  }
}

您可以将绑定处理程序分配给实例的属性,然后将该绑定处理程序传递给addEventListener以及以后的removeEventListener

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

另一种可能性是绑定在构造函数中:

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

您可以将转换handle的方法来箭头功能,那么this将被保留。

  handle = () => {
    // do stuff
    console.log(this.element);
  }
  相关解决方案