Skip to content

Use abortcontroller to simplify connectedCallback #55

@keithamus

Description

@keithamus

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()
  }

}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions