Skip to content

Support AbortSignals in addEventListeners options to unsubscribe from events? #911

Closed
@benjamingr

Description

@benjamingr

Since Node added (experimental) support for AbortController, we have also added support for out event utility functions (that already work with EventTargets) for cancellation:

import { once, EventEmitter } from 'events';
import { setTimeout } from 'timers/promises;

const et = new EventTarget();
const ee = new EventEmitter();
const ac = new AbortController();

setTimeout(100).then(() => ac.abort());

let { signal } = ac;
// run with experimental tla flag or wrap in an iife
await once(ee, 'foo', { signal }); // cancel waiting for the event, removes the listener
await once(et, 'foo', { signal }); // same thing, with event target, removes the listener
for await(const item of on(ee, 'foo' , { signal } )) { // same thing, but with async iterator variant
}

It would be useful to "upstream" this behaviour to the DOM specification as it would be useful to have in browsers:

// Does not yet work, suggested:
const ac = new AbortController();
let { signal } = ac;
const et = new EventTarget();
et.addEventListener('foo', (e) => {
  
}, { signal } );
ac.abort(); // removes the listener from the event target, same as et.removeEventListener('foo', thatFunctionReference)

It's useful to use the web's cancellation platform (AbortController) to cancel listening to an event. This is also ergonomic for frameworks/libraries that set up a lot of event listeners and could unsubscribe from all of them in one go (through the controller).

Was this suggested at some point in the past? (I couldn't find it) Is this a good idea? A bad idea?

cc @domenic @annevk

Metadata

Metadata

Assignees

No one assigned

    Labels

    addition/proposalNew features or enhancementsimpacts documentationUsed by documentation communities, such as MDN, to track changes that impact documentationneeds implementer interestMoving the issue forward requires implementers to express interesttopic: abortingAbortController and AbortSignaltopic: events

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions