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

Use abortcontroller to simplify connectedCallback #55

Open
keithamus opened this issue Dec 2, 2021 · 0 comments
Open

Use abortcontroller to simplify connectedCallback #55

keithamus opened this issue Dec 2, 2021 · 0 comments

Comments

@keithamus
Copy link
Member

keithamus commented Dec 2, 2021

Per #53 (comment), we register many event handlers like addEventlistener('foo', this.bar = this.bar.bind(bar)), but rather than calling function bind we can use handleEvent and rather than calling removeEventListener a bunch, we can store an abort controller per-instance (e.g. with a private field) and abort during disconnectedCallback.

The pattern would look as follows:

class MyElement extends HTMElement {
  #ctl = new AbortController()

  connectedCallback() {
    this.input.addEventListener('foo', this, { signal: this.#ctl.signal })
    // many more events here...
  }

  handleEvent(event) {
    if (event.type === 'foo' && event.currentTarget === this.input) {
      // do things
    }
  }

  disconnectedCallback() {
    this.#ctl.abort()
  }

}
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