Node.js事件发射器2;如何删除使用 onAny 添加的监听器

Node.js EventEmitter2; How to remove listeners added with onAny

如何删除所有侦听 任何 事件的事件侦听器?

我已经尝试 removeAllListeners() 但它不起作用。我错过了什么吗?

const ee = new EventEmitter2()
  
ee.onAny(() => console.log('hello was fired'))
setInterval(() => ee.emit('hello'), 500)

setTimeout(() => {
  ee.removeAllListeners()
  console.log('removed all listeners')
}, 1500)
<script src="https://cdn.jsdelivr.net/npm/eventemitter2@5.0.1/lib/eventemitter2.min.js"></script>

似乎这个库的 API 有点令人困惑。要取消注册 onAny() 个侦听器,请使用 offAny()

深入研究源代码会发现 removeAllListeners() 并没有真正触及跟踪任何事件侦听器的 _all 数组。它只是再次在侦听器上运行 init()configure() none,其中触及 _all 数组。

同时在 GitHub 页面上记录您的问题:removeAllListeners does not remove listeners added with onAny #235

如果你想真正删除它们,请执行以下操作:

const ee = new EventEmitter2();

ee.onAny(() => console.log("any event was fired"));
ee.on("hello", () => console.log("hello event was fired"));

setInterval(() => ee.emit("hello"), 500);

setTimeout(() => {
  console.log("Removing any listener");
  ee.offAny();
}, 1500);

setTimeout(() => {
  console.log("Removing all listeners");
  ee.removeAllListeners();
}, 3000);
<script src="https://cdn.jsdelivr.net/npm/eventemitter2@5.0.1/lib/eventemitter2.min.js"></script>