From ca0179d6a320f1578cfd28f94d1b4decd104d4c5 Mon Sep 17 00:00:00 2001 From: Ultroncn <82553854+Ultroncn@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:34:18 +0000 Subject: [PATCH 1/3] Add once() method Register a handler that is invoked at most once, as requested in #136. The handler removes itself before its first invocation, so it fires exactly once even if it throws, and it can also be removed beforehand with off(type, handler): a once() wrapper is matched through the original handler, and like Node's removeListener the first matching listener is removed. Includes runtime tests, type tests and a README API entry. Fixes #136. --- README.md | 17 +++++++- src/index.ts | 43 +++++++++++++++++++- test/index_test.ts | 72 ++++++++++++++++++++++++++++++++++ test/test-types-compilation.ts | 19 +++++++++ 4 files changed, 148 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 0219f3a..b81629b 100644 --- a/README.md +++ b/README.md @@ -130,10 +130,12 @@ const emitter: Emitter = mitt(); - [all](#all) - [on](#on) - [Parameters](#parameters) -- [off](#off) +- [once](#once) - [Parameters](#parameters-1) -- [emit](#emit) +- [off](#off) - [Parameters](#parameters-2) +- [emit](#emit) + - [Parameters](#parameters-3) ### mitt @@ -154,6 +156,17 @@ Register an event handler for the given type. - `type` **([string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [symbol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol))** Type of event to listen for, or `'*'` for all events - `handler` **[Function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function)** Function to call in response to given event +### once + +Register an event handler for the given type that is invoked at most once. +The handler is removed after its first invocation, and can also be +removed beforehand with `off(type, handler)`. + +#### Parameters + +- `type` **([string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [symbol](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Symbol))** Type of event to listen for, or `'*'` for all events +- `handler` **[Function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function)** Function to call in response to given event + ### off Remove an event handler for the given type. diff --git a/src/index.ts b/src/index.ts index 17672aa..fd45728 100644 --- a/src/index.ts +++ b/src/index.ts @@ -26,6 +26,12 @@ export interface Emitter> { on(type: Key, handler: Handler): void; on(type: '*', handler: WildcardHandler): void; + once( + type: Key, + handler: Handler + ): void; + once(type: '*', handler: WildcardHandler): void; + off( type: Key, handler?: Handler @@ -51,6 +57,10 @@ export default function mitt>( | WildcardHandler; all = all || new Map(); + // Maps a `once()` wrapper back to the handler it was registered with, + // so `off(type, handler)` can remove it like Node's `removeListener`. + const onceHandlers = new WeakMap(); + return { /** * A Map of event names to registered handler functions. @@ -72,6 +82,31 @@ export default function mitt>( } }, + /** + * Register an event handler for the given type that is invoked at most once. + * The handler is removed after its first invocation, and can also be + * removed beforehand with `off(type, handler)`. + * @param {string|symbol} type Type of event to listen for, or `'*'` for all events + * @param {Function} handler Function to call in response to given event + * @memberOf mitt + */ + once(type: Key, handler: GenericEventHandler) { + const wrapper = ((...args: Array) => { + const handlers: Array | undefined = all!.get(type); + if (handlers) { + handlers.splice(handlers.indexOf(wrapper) >>> 0, 1); + } + (handler as (...args: Array) => void)(...args); + }) as GenericEventHandler; + onceHandlers.set(wrapper, handler); + const handlers: Array | undefined = all!.get(type); + if (handlers) { + handlers.push(wrapper); + } else { + all!.set(type, [wrapper] as EventHandlerList); + } + }, + /** * Remove an event handler for the given type. * If `handler` is omitted, all handlers of the given type are removed. @@ -83,7 +118,13 @@ export default function mitt>( const handlers: Array | undefined = all!.get(type); if (handlers) { if (handler) { - handlers.splice(handlers.indexOf(handler) >>> 0, 1); + // A handler registered via `once()` is stored as a wrapper, + // so match it through the original handler. Like Node's + // `removeListener`, the first matching listener is removed. + const index = handlers.findIndex( + (h) => h === handler || onceHandlers.get(h) === handler + ); + handlers.splice(index >>> 0, 1); } else { all!.set(type, []); } diff --git a/test/index_test.ts b/test/index_test.ts index 31c9495..a4b0eb8 100644 --- a/test/index_test.ts +++ b/test/index_test.ts @@ -157,6 +157,78 @@ describe('mitt#', () => { }); }); + describe('once()', () => { + it('should be a function', () => { + expect(inst).to.have.property('once').that.is.a('function'); + }); + + it('should invoke handler only once', () => { + const foo = spy(); + inst.once('foo', foo); + inst.emit('foo'); + inst.emit('foo'); + expect(foo).to.have.been.calledOnce; + }); + + it('should pass the event to the handler', () => { + const event = { a: 'b' }; + const foo = spy(); + inst.once('foo', foo); + inst.emit('foo', event); + expect(foo).to.have.been.calledOnce.and.calledWith(event); + }); + + it('should invoke * handlers only once', () => { + const star = spy(); + inst.once('*', star); + inst.emit('foo', 'a'); + inst.emit('bar', 'b'); + expect(star).to.have.been.calledOnce.and.calledWith('foo', 'a'); + }); + + it('should allow removing a once handler with off() before it fires', () => { + const foo = spy(); + inst.once('foo', foo); + inst.off('foo', foo); + inst.emit('foo'); + expect(foo).to.not.have.been.called; + }); + + it('should remove the once handler even if it throws', () => { + const foo = spy(() => { + throw new Error('boom'); + }); + inst.once('foo', foo); + expect(() => inst.emit('foo')).to.throw('boom'); + inst.emit('foo'); + expect(foo).to.have.been.calledOnce; + }); + + it('should remove the first matching listener when combined with on()', () => { + // `on` first, then `once`: off() removes the `on` registration, + // so the `once` handler still fires exactly once. + const foo = spy(); + inst.on('foo', foo); + inst.once('foo', foo); + inst.off('foo', foo); + inst.emit('foo'); + inst.emit('foo'); + expect(foo).to.have.been.calledOnce; + }); + + it('should remove the once handler first when it was registered first', () => { + // `once` first, then `on`: off() removes the `once` handler, + // so the `on` registration keeps firing. + const foo = spy(); + inst.once('foo', foo); + inst.on('foo', foo); + inst.off('foo', foo); + inst.emit('foo'); + inst.emit('foo'); + expect(foo).to.have.been.calledTwice; + }); + }); + describe('emit()', () => { it('should be a function', () => { expect(inst).to.have.property('emit').that.is.a('function'); diff --git a/test/test-types-compilation.ts b/test/test-types-compilation.ts index 476e631..b59e609 100644 --- a/test/test-types-compilation.ts +++ b/test/test-types-compilation.ts @@ -38,6 +38,25 @@ const wildcardHandler = ( emitter.on('*', barHandler); } +/* + * Check that 'once' args are inferred correctly + */ +{ + // @ts-expect-error + emitter.once('foo', barHandler); + emitter.once('foo', fooHandler); + + emitter.once('bar', barHandler); + // @ts-expect-error + emitter.once('bar', fooHandler); + + emitter.once('*', wildcardHandler); + // fooHandler is ok, because ('foo' | 'bar' | 'someEvent') extends string + emitter.once('*', fooHandler); + // @ts-expect-error + emitter.once('*', barHandler); +} + /* * Check that 'off' args are inferred correctly */ From 755c29e42aa0d5d50089b330d8e2dd52c1e16b48 Mon Sep 17 00:00:00 2001 From: Ultroncn <82553854+Ultroncn@users.noreply.github.com> Date: Wed, 18 Nov 2026 03:17:59 +0000 Subject: [PATCH 2/3] fix(once): address Codex review findings Guard once() wrappers with a fired flag so a synchronous nested re-emit cannot invoke the handler twice through emit()'s snapshot; share the wrapper-to-handler map at module scope so off() works through any emitter sharing the handler map; replace Array.prototype.findIndex in off() with a plain loop to keep IE11 working within the README's advertised IE9+ support. Adds regression tests for all three. --- src/index.ts | 37 ++++++++++++++++++++++------ test/index_test.ts | 60 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 90 insertions(+), 7 deletions(-) diff --git a/src/index.ts b/src/index.ts index fd45728..e8d600e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -44,6 +44,14 @@ export interface Emitter> { ): void; } +/** + * Maps a `once()` wrapper back to the handler it was registered with, + * so `off(type, handler)` can remove it like Node's `removeListener`. + * It lives at module scope so emitters sharing one handler map + * (`mitt(existingMap)`) can all resolve wrappers registered by any of them. + */ +const onceHandlers = new WeakMap(); + /** * Mitt: Tiny (~200b) functional event emitter / pubsub. * @name mitt @@ -57,10 +65,6 @@ export default function mitt>( | WildcardHandler; all = all || new Map(); - // Maps a `once()` wrapper back to the handler it was registered with, - // so `off(type, handler)` can remove it like Node's `removeListener`. - const onceHandlers = new WeakMap(); - return { /** * A Map of event names to registered handler functions. @@ -91,7 +95,16 @@ export default function mitt>( * @memberOf mitt */ once(type: Key, handler: GenericEventHandler) { + let fired = false; const wrapper = ((...args: Array) => { + // emit() invokes handlers from a snapshot, so when an + // earlier listener re-emits synchronously the nested emit + // would invoke this wrapper and the outer emit would invoke + // it again. Guard on `fired` so it runs at most once. + if (fired) { + return; + } + fired = true; const handlers: Array | undefined = all!.get(type); if (handlers) { handlers.splice(handlers.indexOf(wrapper) >>> 0, 1); @@ -121,9 +134,19 @@ export default function mitt>( // A handler registered via `once()` is stored as a wrapper, // so match it through the original handler. Like Node's // `removeListener`, the first matching listener is removed. - const index = handlers.findIndex( - (h) => h === handler || onceHandlers.get(h) === handler - ); + // A plain loop (no Array.prototype.findIndex) keeps this + // working on IE11, within the README's advertised IE9+ + // support. + let index = -1; + for (let i = 0; i < handlers.length; i++) { + if ( + handlers[i] === handler || + onceHandlers.get(handlers[i]) === handler + ) { + index = i; + break; + } + } handlers.splice(index >>> 0, 1); } else { all!.set(type, []); diff --git a/test/index_test.ts b/test/index_test.ts index a4b0eb8..106d561 100644 --- a/test/index_test.ts +++ b/test/index_test.ts @@ -227,6 +227,66 @@ describe('mitt#', () => { inst.emit('foo'); expect(foo).to.have.been.calledTwice; }); + + it('should invoke handler only once when an earlier listener re-emits', () => { + // The outer emit() keeps a snapshot of the handlers, so without + // a fired guard the wrapper is invoked once by the nested emit + // and once more by the outer emit. + const foo = spy(); + let reemitted = false; + inst.on('foo', () => { + if (!reemitted) { + reemitted = true; + inst.emit('foo'); + } + }); + inst.once('foo', foo); + inst.emit('foo'); + expect(foo).to.have.been.calledOnce; + }); + + it('should invoke * handlers only once when an earlier listener re-emits', () => { + const star = spy(); + let reemitted = false; + inst.on('*', () => { + if (!reemitted) { + reemitted = true; + inst.emit('foo', 'a'); + } + }); + inst.once('*', star); + inst.emit('foo', 'a'); + expect(star).to.have.been.calledOnce.and.calledWith('foo', 'a'); + }); + + it('should allow removing a once handler through an emitter sharing the map', () => { + // `mitt(existingMap)` shares the handler map, so off() must + // resolve the once() wrapper through shared metadata, not + // through state private to the registering emitter. + const foo = spy(); + const other = mitt(events); + inst.once('foo', foo); + other.off('foo', foo); + inst.emit('foo'); + expect(foo).to.not.have.been.called; + }); + + it('should remove handlers without Array.prototype.findIndex', () => { + // IE11 (within the README's advertised IE9+ support) has no + // Array.prototype.findIndex, so off() must not rely on it. + const foo = spy(); + const findIndex = Array.prototype.findIndex; + // @ts-expect-error testing an environment without findIndex (IE11) + Array.prototype.findIndex = undefined; + try { + inst.on('foo', foo); + inst.off('foo', foo); + inst.emit('foo'); + } finally { + Array.prototype.findIndex = findIndex; + } + expect(foo).to.not.have.been.called; + }); }); describe('emit()', () => { From 8af2b606cda9d52113f2f9de338d1f392eac6db4 Mon Sep 17 00:00:00 2001 From: Ultron <82553854+Ultroncn@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:32:59 +0800 Subject: [PATCH 3/3] fix: keep once handlers compatible without WeakMap --- src/index.ts | 43 +++++++++++++++++++++++++++++-------------- test/index_test.ts | 25 +++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 14 deletions(-) diff --git a/src/index.ts b/src/index.ts index e8d600e..987728b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -44,13 +44,8 @@ export interface Emitter> { ): void; } -/** - * Maps a `once()` wrapper back to the handler it was registered with, - * so `off(type, handler)` can remove it like Node's `removeListener`. - * It lives at module scope so emitters sharing one handler map - * (`mitt(existingMap)`) can all resolve wrappers registered by any of them. - */ -const onceHandlers = new WeakMap(); +const onceHandlerKey = '__mittOnce'; +const onceHandlerMarker = {}; /** * Mitt: Tiny (~200b) functional event emitter / pubsub. @@ -63,6 +58,10 @@ export default function mitt>( type GenericEventHandler = | Handler | WildcardHandler; + type OnceHandlerMetadata = { + marker: typeof onceHandlerMarker; + handler: GenericEventHandler; + }; all = all || new Map(); return { @@ -111,7 +110,11 @@ export default function mitt>( } (handler as (...args: Array) => void)(...args); }) as GenericEventHandler; - onceHandlers.set(wrapper, handler); + // Store the handler on its wrapper so emitters sharing a map + // can identify it without requiring WeakMap. + Object.defineProperty(wrapper, onceHandlerKey, { + value: { marker: onceHandlerMarker, handler } + }); const handlers: Array | undefined = all!.get(type); if (handlers) { handlers.push(wrapper); @@ -139,13 +142,25 @@ export default function mitt>( // support. let index = -1; for (let i = 0; i < handlers.length; i++) { - if ( - handlers[i] === handler || - onceHandlers.get(handlers[i]) === handler - ) { - index = i; - break; + const listener = handlers[i]; + if (listener !== handler) { + const descriptor: PropertyDescriptor | undefined = + typeof listener === 'function' + ? Object.getOwnPropertyDescriptor(listener, onceHandlerKey) + : undefined; + const metadata: OnceHandlerMetadata | undefined = descriptor + ? descriptor.value + : undefined; + if ( + !metadata || + metadata.marker !== onceHandlerMarker || + metadata.handler !== handler + ) { + continue; + } } + index = i; + break; } handlers.splice(index >>> 0, 1); } else { diff --git a/test/index_test.ts b/test/index_test.ts index 106d561..ef70944 100644 --- a/test/index_test.ts +++ b/test/index_test.ts @@ -1,7 +1,9 @@ import mitt, { Emitter, EventHandlerMap } from '..'; import chai, { expect } from 'chai'; +import { readFileSync } from 'fs'; import { spy } from 'sinon'; import sinonChai from 'sinon-chai'; +import { runInNewContext } from 'vm'; chai.use(sinonChai); describe('mitt', () => { @@ -20,6 +22,29 @@ describe('mitt', () => { expect(a).to.have.been.calledOnce; expect(b).to.have.been.calledOnce; }); + + it('should work with Map available but no WeakMap', () => { + const source = readFileSync(require.resolve('..'), 'utf8'); + const loadMitt = runInNewContext(source + '\nmodule.exports;', { + Map, + WeakMap: undefined, + module: { exports: {} } + }) as typeof mitt; + const emitter = loadMitt<{ foo: undefined }>(); + const other = loadMitt(emitter.all); + const listener = spy(); + const cancelled = spy(); + + emitter.on('foo', listener); + emitter.once('foo', cancelled); + other.off('foo', cancelled); + other.emit('foo'); + other.off('foo', listener); + other.emit('foo'); + + expect(listener).to.have.been.calledOnce; + expect(cancelled).to.not.have.been.called; + }); }); describe('mitt#', () => {