How can I handle multiple events with the same event handler function using Node.js EventEmitter?

Viewed 548

To simplify my problem a little bit let's break it down the following easy example.

I have multiple event-listeners listening for different things but in the end, I always want to call the same handler function. I know I can do something like this:

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");

However, as you can see the code is repeating over and over again. I wonder if there is a handy workaround or another option that makes this easier. Maybe something similar to emitter.on(["runninwith", "sympathyfor", "shoutat"], handler); (Obviously doesn't work)?

In short, is there a way to call the same event handler function when different events are fired?

0 Answers
Related