NodeJS EventEmitter : use event name as "*"(asterisk)

838 Views Asked by At

I'm trying to understand some snippet of code from one open-source project where I don't understand what means to call EventEmitter.emit with the asterisk '*' as an event name.

In some libs (like JQuery), '*' as an event name means 'all events'.

What does it mean within the context of the EventEmitter?

I tried to find a listener for the '*' event in this project, but no luck.

class BlaBla extends EventEmitter {

    methodCall(event){
        this.emit("*", {event}); // <- what does this mean ???
    }
}
2

There are 2 best solutions below

1
On

this.emit("*", {event}); means that Calling the emit() method will execute all the functions that are registered with the on method.

0
On

Using '*' as an event name has no special effects, it behaves as a normal event.

You can take a look at the event emitter code and see that the only special event names are:

Example (repl.it code)

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

class BlaBla extends EventEmitter {

  methodCall(stuff) {
    this.emit("*", {
      stuff // <-- this gets passed as an argument to the handler for the '*' event
    });
  }
}

const b = new BlaBla();

b.on('a', (...args) => console.log('nope', ...args)); // <-- this doesn't run
b.on('b', (...args) => console.log('nope', ...args)); // <-- this doesn't run
b.on('*', (...args) => console.log('this gets called', ...args)); // <-- This runs

b.methodCall('this gets passed down');

Output

this gets called { stuff: 'this gets passed down' }

If in this particular project all event handlers get called when this.emit('*') is called, they are probably doing this manually.

Here's a simplified example of how it can be done:

const eventNames = ['a', 'b', 'c'];

this.on('*', () =>
  eventNames.forEach(event => this.emit(event))
);