I have tried to write an eventEmitter
class following explanation on these link
but when I wrote my own code
class EventEmitter {
constructor() {
this.listeners = {};
}
addListener(eventName, fn) {
this.listeners[eventName] = this.listeners[eventName] || [];
this.listeners[eventName].push(fn)
return this;
}
on(eventName, fn) {
this.addListener(eventName, fn);
return this;
}
removeListener(eventName, fn) {
if (!this.listeners[eventName] || this.listeners[eventName].length === 0) {
return;
}
const index = this.listeners[eventName].indexOf(fn);
this.listeners[eventName].splice(index, 1);
}
off(eventName, fn) {
this.removeListener(eventName, fn);
}
once(eventName, fn) {
this.listeners[eventName] = this.listeners[eventName] || [];
const onceWrapper = (...args) => {
fn(...args);
this.removeListener(eventName, onceWrapper);
}
this.listeners[eventName].push(onceWrapper);
return this;
}
emit(eventName, ...args) {
this.listeners[eventName].forEach(fn => {
fn(...args);
});
return this;
}
}
const obj = new EventEmitter();
const c1 = () => {
console.log("Callback 1");
}
const c2 = () => {
console.log("Callback 2");
}
const c3 = (x) => {
console.log(`Callback ${x}`);
}
obj.once("foo", c1);
obj.once("foo", c2);
obj.once("foo", c3);
obj.emit("foo", 3)
the output was logged
Callback 1
Callback 3
not
Callback 1
Callback 2
Callback 3
I printed the listeners["foo"].length
before calling emit()
and after was first 3 then 1 it acted like skipping c2. I do not know the reason which does not make forEach
loop on all items and I also tried to add more callbacks but also it dose not call all functions
New contributor
Nayra Youssef is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.