[WICG/webcomponents] Tie in AbortControllers with CustomElements (Issue #1061)

See https://github.com/whatwg/html/issues/9881

I think exposing an `AbortSignal` as part of the ElementInternals would be an ergonomic simplification around reversing the operations in a `connectedCallback()` (e.g. by passing a `signal` to eventlisteners or fetch calls).

> ### What problem are you trying to solve?
> 
> It's quite common to want to bind to event listeners on global objects, or parent objects to take advantages of delegate event listening. Doing so requires tearing down those listeners, which can be a little cumbersome.
> ### What solutions exist today?
> 
> `AbortController` makes this easier but it can still involve a fair amount of boilerplate; here's the minimum viable code to register an event listener with appropriate `AbortController` code:
> 
> class MyElement extends HTMLElement {
>   #controller = null;
>   connectedCallback() {
>     this.#controller?.abort();
>     const signal = this.#controller = new AbortController();
>     this.ownerDocument.addEventListener('whatever', e => {}, {signal});
>   }
>   disconnectedCallback() {
>     this.#controller?.abort();
>   }
> }
> 
> ### How would you solve it?
> 
> I'd like to introduce an AbortSignal _intrinsic_ to the CE lifecycle, one that gets automatically set up _just before_ `connectedCallback()` and gets aborted _just before_ (or maybe _just after_?) `disconnectedCallback()`. In doing so, the above code could become something like:
> 
> class MyElement extends HTMLElement {
>   #internals = this.elementInternals();
>   connectedCallback() {
>     const signal = this.#internals.connectedSignal();
>     this.ownerDocument.addEventListener('whatever', e => {}, {signal});
>   }
> }
> 
> Whenever an element gets connected, it would abort and dispose of its associated connectedSignal, and create a new one. Calling `this.#internals.connectedSignal()` would return the _current_ associated connectedSignal. When an element disconnects from the DOM, it would abort its associated signal.
> 
> This would alleviate much of the work around creating and managing an `AbortController` just to abstract the work of connectedCallback/disconnectedCallback.
> ### Anything else?
> 
> _No response_



-- 
Reply to this email directly or view it on GitHub:
https://github.com/WICG/webcomponents/issues/1061
You are receiving this because you are subscribed to this thread.

Message ID: <WICG/webcomponents/issues/1061@github.com>

Received on Wednesday, 26 June 2024 17:50:40 UTC