Re: [whatwg/dom] once() and on() async utilities for EventTarget (Issue #1038)

> I do think there are cases where you would want `next()` and cancelability, e.g., for the `click` event.

There are a few simple options, one would be just to accept a sync handler step i.e.:

```js
const event = await target.once("some-event", { 
    handleSync: (event) => {
        if (someCondition) event.preventDefault();
    },
});
```

Alternatively `once` already works for DOM events if you immediately `await` it i.e.:

```js
const event = await element.once("click");
// Still works
event.preventDefault();
```

However this does depend on the weird zalgo behaviour that events dispatched by the user agent have microtask checkpoints after firing event listeners but before finishing the event, this power can't be accessed by userland events in any way.

And although this behaviour is fairly zalgo, some libraries such as [idb](https://www.npmjs.com/package/idb) do actually depend on that exact behaviour†, so it's not particularly uncharted terrority.

† For that library specifically indexedDB fires events for transactions, once the event is over the transaction is no longer usable, however because it's a UA event one can schedule microtasks (e.g. via `await`) just fine and the transaction is still usable, as such the library is able to wrap things in promises and as long as the promises are immediately awaited everything works out.

Another another model could be that `.once` actually takes an optional callback function, however the return value of that callback is wrapped in a promise and returned i.e.:

```js
const x = await element.once("click", async (event) => {
    // All code prior to an await is run synchronously, so event.preventDefault is fine here
    if (someCondition) event.preventDefault();
    return event.x;
});
```

This is considerably less zalgo than the above, but does require a somewhat different structure for code.

-- 
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#issuecomment-984427319

Received on Thursday, 2 December 2021 09:04:29 UTC