javascript
43 lines · 7 steps
Building an EventEmitter in JavaScript
A pub/sub class that registers handlers per event, supports one-shot listeners, and fires them on emit.
Explained by
highlit
1class EventEmitter {
2 constructor() {
3 this.listeners = new Map();
4 }
5
6 on(event, handler) {
7 if (!this.listeners.has(event)) {
8 this.listeners.set(event, new Set());
9 }
10 this.listeners.get(event).add(handler);
11 return this;
12 }
13
14 once(event, handler) {
15 const wrapper = (...args) => {
16 this.off(event, wrapper);
17 handler(...args);
18 };
19 wrapper.original = handler;
20 return this.on(event, wrapper);
21 }
22
23 off(event, handler) {
24 const handlers = this.listeners.get(event);
25 if (!handlers) return this;
26 for (const h of handlers) {
27 if (h === handler || h.original === handler) {
28 handlers.delete(h);
29 }
30 }
31 if (handlers.size === 0) this.listeners.delete(event);
32 return this;
33 }
34
35 emit(event, ...args) {
36 const handlers = this.listeners.get(event);
37 if (!handlers) return false;
38 for (const handler of [...handlers]) {
39 handler(...args);
40 }
41 return true;
42 }
43}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A Map of event names to Sets gives fast lookup and automatic dedup of handlers.
- 2Wrapping a handler in a self-removing closure turns any listener into a one-shot without new machinery.
- 3Tagging the wrapper with a reference to the original handler lets off() cancel once-listeners by their public identity.
Related explainers
javascript
const RESERVED_SLUGS = new Set(['new', 'edit', 'admin', 'api']); function slugify(title) { return title
Generating URL-safe unique slugs
string-normalization
regex
deduplication
Intermediate
9 steps
javascript
const express = require('express'); const compression = require('compression'); const zlib = require('zlib');
Tuning Express response compression
compression
middleware
http
Intermediate
9 steps
javascript
import { NextResponse } from 'next/server' const UPSTREAM = 'https://api.exchangerate.host/latest'
A cached exchange-rate proxy in Next.js
route-handler
caching
revalidation
Intermediate
7 steps
javascript
const logger = require('./logger'); class AppError extends Error { constructor(message, statusCode = 500, details = null) {
Centralized error handling in Express
error-handling
middleware
custom-errors
Intermediate
8 steps
javascript
const formatters = new Map(); function getFormatter(locale, currency) { const key = `${locale}:${currency}`;
Caching Intl.NumberFormat for currency formatting
memoization
internationalization
caching
Intermediate
8 steps
javascript
class DOMBatcher { constructor() { this.reads = []; this.writes = [];
Batching DOM reads and writes to avoid layout thrash
batching
requestanimationframe
layout-thrashing
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-an-eventemitter-in-javascript-explained-javascript-1679/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.