Event Emitter Pattern in JavaScript
Level 5484 keystrokes
This implements a simple event emitter with subscribe and publish pattern.
JavaScript code
// EventEmitter class implements the observer pattern1class EventEmitter {2 constructor() { // Object to store event listeners // Key: event name, Value: array of listener functions3 this.events = {};4 }5 // Subscribe a listener to an event6 on(event, listener) { // Create array for this event if it doesn't exist7 if (!this.events[event]) {8 this.events[event] = [];9 } // Add the listener to the event's array10 this.events[event].push(listener);11 }12 // Emit an event, calling all subscribed listeners13 emit(event, ...args) { // Check if there are any listeners for this event14 if (this.events[event]) { // Call each listener with the provided arguments15 this.events[event].forEach(listener => {16 listener(...args);17 });18 }19 }20}21 // Create an instance of EventEmitter22const emitter = new EventEmitter();// Subscribe two listeners to the "greet" event23emitter.on("greet", name => console.log(`Hello, ${name}!`));24emitter.on("greet", name => console.log(`Hi there, ${name}!`));// Emit the "greet" event with "Alice" as argument// Both listeners will be called25emitter.emit("greet", "Alice");Output
Hello, Alice! Hi there, Alice!
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this JavaScript code and how often they appear.
.× 19(× 14)× 14{× 10}× 10;× 9"× 8,× 7[× 6]× 6