Add/remove 事件监听器,同时保持 "this" 的实例上下文

Add/remove eventListeners while keeping instance context of "this"

我正在尝试使用 vanilla JS 事件系统在我的浏览器应用程序的不同组件之间发送事件(不涉及 NodeJS),方法是将事件分派给 window 对象。

// method in Class A
sendDone() {
  window.dispatchEvent(new Event('done');
}

在另一个 class 中,我有一个方法可以处理此事件的 optional 侦听器,用户可以 enabled/disabled。

// method in Class B
setOption(shouldListen) {
  if (shouldListen) {
    window.addEventListener('done', this.doneHandler);
  } else {
    window.removeEventListener('done', this.doneHandler);
  }
}

但是,处理程序获取 window 上下文而不是实例上下文,并且 this 关键字没有像我希望的那样工作:

// method in Class B
doneHandler() {
  this.someMethod(this.someValue);  // doesn't work
}

我无法将 this 传递给具有匿名函数的处理程序,因为我无法从侦听器列表中删除匿名函数。出于同样的原因,我不能在函数定义中包含处理程序代码,如下所示:

const self = this;
window.addEventListener('done', function() {
  // can use self here instead
  // but listener still can't be removed
});

我是 JS 的新手,我想知道通常如何处理这种情况。

谢谢。

您需要在 class:

的构造函数中使用 Function.prototype.bind()
constructor() {
    this.doneHandler = this.doneHandler.bind(this);
}

其余代码不会更改,所以现在您可以添加和删除事件侦听器。