Skip to content

Instantly share code, notes, and snippets.

@cs-fedy
Created April 20, 2021 17:31
Show Gist options
  • Save cs-fedy/28a342f30b76f5a5d4eb7d14b80ea7c5 to your computer and use it in GitHub Desktop.
Save cs-fedy/28a342f30b76f5a5d4eb7d14b80ea7c5 to your computer and use it in GitHub Desktop.
function Emitter() {
this.events = {};
}
Emitter.prototype.addListener = function (type, listener) {
// check if the listener is a function and throw error if it is not
if (typeof listener !== "function") {
throw new Error("Listener must be a function!");
}
// create the event listener property (array) if it does not exist.
this.events[type] = this.events[type] || [];
// adds listners to the events array.
this.events[type].push(listener);
};
Emitter.prototype.on = function (type, listener) {
return this.addListener(type, listener);
};
Emitter.prototype.listenerCount = function (type) {
let listenersCount = 0;
let listeners = this.events[type] || [];
listenersCount = listeners.length;
console.log("listenersCount", listenersCount);
return listenersCount;
};
Emitter.prototype.emit = function (type) {
if (this.events[type]) {
// checks if event is a property on Emitter
this.events[type].forEach(function (listener) {
// loop through that events array and invoke all the listeners inside it.
listener();
});
}
};
const eventEmitter = new Emitter();
eventEmitter.on("greet", () => {
console.log("Hello World!");
});
eventEmitter.on("greet", () => {
console.log("Hello from LogRocket!");
});
eventEmitter.on("greet", () => {
console.log("Hello from Eagles!");
});
eventEmitter.listenerCount("greet");
eventEmitter.emit("greet"); // manually emit an event
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment