Skip to content

events: add addDisposableListener method to EventEmitter#58453

Closed
jasnell wants to merge 1 commit intonodejs:mainfrom
jasnell:jasnell/eventemitter-using
Closed

events: add addDisposableListener method to EventEmitter#58453
jasnell wants to merge 1 commit intonodejs:mainfrom
jasnell:jasnell/eventemitter-using

Conversation

@jasnell
Copy link
Member

@jasnell jasnell commented May 25, 2025

This adds new use(...) and useOnce(...) methods addDisposableListener method to EventEmitter that returns a disposable object that will unregister the event listeners when disposed, along with two changes that use the new apis to demonstrate how it can be used to simplify some cleanup.

const ee = new EventEmitter();
{
  using ds = new DisposableStack();
  ds.use(ee.addDisposableListener('foo', () => {});
  ds.use(ee.addDisposableListener('bar', () => {});
  if (something) ds.use(ee.addDisposableListener('baz', () => {});
}
// The event listeners will all be removed automatically when ds is disposed.
// We don't need to separately remember to call removeListener/off to cleanup the event listeners

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

Labels

author ready PRs that have at least one approval, no pending requests for changes, and a CI started. events Issues and PRs related to the events subsystem / EventEmitter. experimental Issues and PRs related to experimental features. needs-ci PRs that need a full CI run. semver-minor PRs that contain new features and should be released in the next minor version. stream Issues and PRs related to the stream subsystem. test_runner Issues and PRs related to the test runner subsystem.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants