Course contentsShow
← JavaScript
Lesson 2419 of 2,72349. Common Patterns and IdiomsFree lesson

One-Time Listeners with once()

Registering listeners that automatically unsubscribe after their first invocation.

One-Time Listeners with once()

What you'll learn: How to register event listeners that automatically remove themselves after firing once, eliminating the need for manual cleanup.

The Problem with Regular Listeners

When you use on() to register a listener in your event emitter, it stays registered forever—or until you manually call off() to remove it. But sometimes you only care about an event the first time it happens. Maybe you're waiting for a connection to open, or for a user to click "accept" on a one-time modal. Calling the listener again after that would be wasteful or cause bugs.

What once() Does

The once() method registers a listener that automatically unsubscribes itself after its first invocation. Think of it like a self-destructing mission: the listener executes once, then removes itself from the event emitter's internal registry.

Implementing once()

Building on your existing event emitter:

class EventEmitter {
  // ... (existing on, emit, off methods)

  once(event, listener) {
    const wrapper = (...args) => {
      this.off(event, wrapper);  // Remove immediately
      listener(...args);          // Then call the original
    };
    
    this.on(event, wrapper);
  }
}

// Usage
const emitter = new EventEmitter();

emitter.once('connect', () => {
  console.log('Connected! (only once)');
});

emitter.emit('connect');  // Logs: "Connected! (only once)"
emitter.emit('connect');  // Nothing happens

The trick is wrapping the original listener in a function that first removes itself, then invokes the real callback.

Key Takeaway: once() provides automatic listener cleanup after the first event, preventing memory leaks and simplifying code that only needs to react to an event's initial occurrence.