Here is the implementation of the event emitter class:
class EventEmitter {
constructor() {
this.events = {};
}
subscribe(eventName, listener) {
if (!this.events[eventName]) {
this.events[eventName] = [];
}
this.events[eventName].push(listener);
}
unsubscribe(eventName, listener) {
if (this.events[eventName]) {
this.events[eventName] = this.events[eventName].filter((l) => l !== listener);
}
}
emit(eventName, ...args) {
if (this.events[eventName]) {
this.events[eventName].forEach((listener) => listener(...args));
}
}
}
Explanation:
The EventEmitter class is constructed with an empty events object to store the event listeners.
The subscribe method takes an eventName and a listener function. It adds the listener to the corresponding event's array in the events object. If the event doesn't exist, it creates a new array.
The unsubscribe method removes the listener from the array of the given eventName if it exists.
The emit method triggers all the listeners of the given eventName by calling them with any additional arguments passed.
Event Emitter Class
Here is the implementation of the event emitter class:
Explanation:
EventEmitter
class is constructed with an emptyevents
object to store the event listeners.subscribe
method takes aneventName
and alistener
function. It adds thelistener
to the corresponding event's array in theevents
object. If the event doesn't exist, it creates a new array.unsubscribe
method removes thelistener
from the array of the giveneventName
if it exists.emit
method triggers all the listeners of the giveneventName
by calling them with any additional arguments passed.Commit Message: Implement event emitter class