如何使用node.js eventemitter使用相同的事件处理函数处理多个事件?

fxnxkyjh  于 2021-09-23  发布在  Java
关注(0)|答案(0)|浏览(183)

为了稍微简化我的问题,让我们将其分解为以下简单的示例。
我有多个事件侦听器侦听不同的内容,但最后,我总是希望调用同一个处理程序函数。我知道我可以做这样的事情:

const { EventEmitter } = require("events");

const emitter = new EventEmitter();

const handler = () => console.log("the devil");

emitter.on("runninwith", handler);
emitter.on("sympathyfor", handler);
emitter.on("shoutat", handler);

emitter.emit("runninwith");
emitter.emit("sympathyfor");

但是,正如您所看到的,代码正在一次又一次地重复。我想知道是否有一个方便的解决办法或其他选择,使这更容易。也许类似于 emitter.on(["runninwith", "sympathyfor", "shoutat"], handler); (显然不起作用)?
简言之,当触发不同的事件时,是否有方法调用相同的事件处理程序函数?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题