I have a this class:
class test {
constructor(name) {
this.name = name
}
}
So I want to have a event in the class that can be called outside.
Here the full file:
const eventLib = require('events');
const myEmitter = new eventLib.EventEmitter();
class test {
constructor(name) {
this.name = name
}
}
You can either subclass the EventEmitter so that your class has all the same methods as an EventEmitter object or you can put an eventEmitter in your instance data and can use it there.
Here's subclassing it:
const EventEmitter = require('events');
class Test extends EventEmitter {
constructor(name) {
super();
this.name = name
this.on("hi", () => {
console.log("got hi: ", this.name);
});
}
}
let x = new Test("Bob");
x.emit("hi");