Skip to content

Custom Event Emitter

Medium ~35 min

What you'll build

An EventEmitter class with on (subscribe), off (unsubscribe), emit (publish), and once (subscribe for a single emission).

Goals

  • Store listeners in a Map keyed by event name
  • Implement on/off/emit/once methods
  • Support multiple listeners per event
  • Understand the pub/sub decoupling pattern

Prerequisites

  • Objects and Maps
  • Array methods (push, filter)
  • Functions as first-class values

Steps

  1. 1

    Set up the listener store

    Create an EventEmitter class with a Map of event names to listener arrays. The Map is the core data structure for pub/sub.

    Code
    class EventEmitter {
      constructor() {
        this.listeners = new Map();
      }
    }

    Expected result

    An emitter with an empty listeners Map.

  2. 2

    Implement on and emit

    on(event, fn) adds fn to the listener array for that event (creating the array if needed). emit(event, ...args) calls every listener with the args.

    Code
    on(event, fn) {
      if (!this.listeners.has(event)) this.listeners.set(event, []);
      this.listeners.get(event).push(fn);
      return this;
    }
    emit(event, ...args) {
      const fns = this.listeners.get(event) || [];
      fns.forEach(fn => fn(...args));
      return this;
    }

    Expected result

    on('greet', console.log); emit('greet', 'hi') logs 'hi'.

  3. 3

    Implement off

    off(event, fn) removes a specific listener. Use filter to keep all listeners except the given function reference.

  4. 4

    Implement once

    once(event, fn) subscribes fn but auto-removes it after the first emission. Implement by wrapping fn in a wrapper that calls fn then calls off.

  5. 5

    Test the emitter

    Subscribe multiple listeners, emit, unsubscribe one, emit again, and test once. Verify the pub/sub decoupling: emitters and listeners don't need to know about each other.

    Code
    const ee = new EventEmitter();
    const handler = (msg) => console.log('A:', msg);
    ee.on('msg', handler);
    ee.on('msg', (msg) => console.log('B:', msg));
    ee.once('msg', (msg) => console.log('Once:', msg));
    ee.emit('msg', 'hello'); // A, B, Once
    ee.emit('msg', 'world'); // A, B (once gone)
    ee.off('msg', handler);
    ee.emit('msg', 'test');  // B only

    Expected result

    First emit prints A, B, Once; second prints A, B; third prints B only.

Try it yourself

What you learned

You built the pub/sub pattern that powers Node's EventEmitter, the DOM, React state libraries, and most message-bus systems — decoupling producers from consumers.

Related Resources

Related Lessons

  • Events

    The event-driven programming model.

  • Objects

    A Map stores listeners by event name.

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to topic