Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tie in AbortControllers with CustomElements #1061

Open
keithamus opened this issue Jun 26, 2024 · 0 comments
Open

Tie in AbortControllers with CustomElements #1061

keithamus opened this issue Jun 26, 2024 · 0 comments

Comments

@keithamus
Copy link
Collaborator

keithamus commented Jun 26, 2024

See whatwg/dom#1296

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant