- From: James M Snell <notifications@github.com>
- Date: Wed, 01 Dec 2021 12:24:04 -0800
- To: whatwg/dom <dom@noreply.github.com>
- Cc: Subscribed <subscribed@noreply.github.com>
Received on Wednesday, 1 December 2021 20:24:16 UTC
A while back Node.js introduced the [`once()`](https://nodejs.org/dist/latest-v17.x/docs/api/events.html#eventsonceemitter-name-options) and [`on()`](https://nodejs.org/dist/latest-v17.x/docs/api/events.html#eventsonemitter-eventname-options) utility functions for Node.js' `EventEmitter` object. They are essentially just promise-based alternatives to adding a callback listener for an event. They've proven to be so useful in practice that I'd like to propose adding similar utilities for `EventTarget`
Essentially,
```js
const ac = new AbortController();
const eventTarget = new EventTarget();
setTimeout(() => eventTarget.dispatchEvent(new Event('foo')), 1000);
// EventTarget.once() returns a Promise that is resolved the next time the event is dispatched.
await EventTarget.once(eventTarget, 'foo', { signal: ac.signal });
```
and
```js
const ac = new AbortController();
const eventTarget = new EventTarget();
setInterval(() => eventTarget.dispatchEvent(new Event('foo')), 1000);
// EventTarget.on() returns an async iterator that iterates each time the event is dispatched.
for await (const ev of EventTarget.on(eventTarget, 'foo', { signal: ac.signal })) {
// ...
}
```
--
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/dom/issues/1038
Received on Wednesday, 1 December 2021 20:24:16 UTC