node js event emitter 1

node js event emitter

const EventEmitter = require('events');

class MyEmitter extends EventEmitter {
  foo() {
    this.emit('test');
  }
}
const myEmitter = new MyEmitter();
myEmitter.on('test', () => console.log('Yay, it works!'));

myEmitter.foo();	// Yay it works!

Here is what the above code is Doing:
1. We create a class called MyEmitter that extends EventEmitter.
2. We create a method called foo that emits a test event.
3. We create an instance of MyEmitter and listen for the test event.
4. We call the foo method.

Similar Posts