Skip to content

Add once() method - #224

Open
Ultroncn wants to merge 3 commits into
developit:mainfrom
Ultroncn:feat/add-once-method
Open

Ultroncn wants to merge 3 commits into
developit:mainfrom
Ultroncn:feat/add-once-method

Conversation

@Ultroncn

Copy link
Copy Markdown

Hi! 👋

Motivation: #136 has asked for an official .once() since 2019, and you noted there that you weren't entirely against adding it, depending on the size impact. This PR adds it.

Change:

  • New once(type, handler) method (plus '*' wildcard support) with the same typed overloads as on(). The handler removes itself before its first invocation, so it fires exactly once even if it throws.
  • off(type, handler) can remove a once() handler beforehand: the wrapper is matched through the original handler, and like Node's removeListener the first matching listener is removed. This covers the on() + once() combination you raised in Support for .once() API #136 — whichever was registered first is the one off() removes.
  • Runtime tests (8 new), type tests, and a README API entry for once().

Size impact (honest note): the bundle grows from ~190 B to ~312 B gzipped (ESM/CJS, per microbundle), so this does push mitt past the 200 B mark. If that's a deal-breaker I'm happy to discuss a smaller variant — I kept the implementation as small as I could while keeping off(type, handler) working for once() handlers.

Verification:

  • npx tsc --noEmit, npx eslint src test, and npx tsc test/test-types-compilation.ts --noEmit --strict all pass.
  • Mocha: 27 passing (19 pre-existing + 8 new once() tests). Note: the repo's stock npm test fails on modern Node before reaching mocha because the legacy esm loader crashes (pre-existing — same on Node 22, see Allow interface event maps in TypeScript #223); I ran mocha directly with --no-package --no-config to skip that loader, which is the only change in how the tests were run.
  • A minimal repro (emitter.once('ready', fn) + two emits) calls the handler exactly once.

Fixes #136. Thanks for considering it!

Register a handler that is invoked at most once, as requested in
developit#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 developit#136.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-18T19:35:52.590448Z 8af2b60 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ca0179d6a3

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/index.ts
Comment on lines +97 to +99
handlers.splice(handlers.indexOf(wrapper) >>> 0, 1);
}
(handler as (...args: Array<unknown>) => void)(...args);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Guard once wrappers against nested emit snapshots

When an earlier listener synchronously re-emits the same event before the once() listener is reached, the nested emit() invokes and removes this wrapper, but the outer emit() still invokes it from its .slice() snapshot. Consequently, a single once('foo', fn) registration calls fn twice; wildcard listeners have the same problem. Track and check a per-wrapper fired flag before invoking the handler, rather than relying solely on removal from the live map.

Useful? React with 👍 / 👎.

Comment thread src/index.ts Outdated
// 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(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep listener removal compatible with IE11

In IE11, which falls within the README's advertised IE9+ support, Array.prototype.findIndex is unavailable. This makes ordinary on('foo', fn); off('foo', fn) usage throw TypeError and leave the listener registered, even when once() is never used. The previous indexOf() implementation worked in this environment. Use an ES5-compatible search to retain wrapper matching without breaking existing listener removal.

Useful? React with 👍 / 👎.

Comment thread src/index.ts Outdated

// 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<GenericEventHandler, GenericEventHandler>();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Share once-handler metadata with the event registry

When two emitters use the same externally supplied handler map, cancellation through the second emitter silently fails for one-shot listeners: with const b = mitt(a.all), the sequence a.once('foo', fn); b.off('foo', fn); b.emit('foo') still invokes fn, whereas the equivalent on() registration is removed correctly. The wrapper lives in the shared map, but only the registering emitter's private WeakMap knows its original handler. Associate that metadata with the wrapper or shared registry so either emitter can remove the pending listener.

Useful? React with 👍 / 👎.

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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 755c29e42a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/index.ts Outdated
* 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<object, object>();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid requiring WeakMap at module load

For IE9/IE10 consumers that provide a Map polyfill but no WeakMap polyfill, this new top-level initializer throws ReferenceError during import, so even existing applications that never use once() stop loading. The parent revision works in that environment, and README.md still advertises IE9+ support. Store the original-handler metadata on the wrapper or provide a compatible fallback rather than making WeakMap an unconditional runtime requirement.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support for .once() API

1 participant