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 pattern
1class EventEmitter {
2 constructor() {
// Object to store event listeners
// Key: event name, Value: array of listener functions
3 this.events = {};
4 }
5
// Subscribe a listener to an event
6 on(event, listener) {
// Create array for this event if it doesn't exist
7 if (!this.events[event]) {
8 this.events[event] = [];
9 }
// Add the listener to the event's array
10 this.events[event].push(listener);
11 }
12
// Emit an event, calling all subscribed listeners
13 emit(event, ...args) {
// Check if there are any listeners for this event
14 if (this.events[event]) {
// Call each listener with the provided arguments
15 this.events[event].forEach(listener => {
16 listener(...args);
17 });
18 }
19 }
20}
21
// Create an instance of EventEmitter
22const emitter = new EventEmitter();
// Subscribe two listeners to the "greet" event
23emitter.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 called
25emitter.emit("greet", "Alice");

Output

Hello, Alice!
Hi there, Alice!
Practice typing this code

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

More JavaScript examples at level 5

← JavaScript typing practice