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

[Tutorial] show using AbortController for simpler cleanup with event listeners #1677

Open
NullVoxPopuli opened this issue Feb 21, 2024 · 1 comment

Comments

@NullVoxPopuli
Copy link
Owner

NullVoxPopuli commented Feb 21, 2024

From @sukima: https://tritarget.org/#examples%2Fpage-unload-management%2Fevent-handler-abort

Instead of:

  @action setupWindowListener() {
    /* setup */
    window.addEventListener('beforeunload', this.handleUnload)

    registerDestructor(this, () => {
      /* teardown */
      window.removeEventListener('beforeunload', this.handleUnload)
    });
  }

Maybe this?

  @action setupWindowListener() {
    /* setup */
    let cleanup = new AbortController();
    let { signal } = cleanup;
    window.addEventListener('beforeunload', this.handleUnload, { signal })

    /* tear down */
    registerDestructor(cleanup, cleanup.abort);
  }
@sukima
Copy link

sukima commented Jun 13, 2024

I think registerDestructor needs this as a first parameter. I believe it needs this to have it participate in the component tear down right?

  @action setupWindowListener() {
    /* setup */
    let cleanup = new AbortController();
    let { signal } = cleanup;
    window.addEventListener('beforeunload', this.handleUnload, { signal })

    /* tear down */
    registerDestructor(this, () => cleanup.abort);
  }

Also in this simple example you can get away with an extra object creation:

  @action setupWindowListener() {
    /* setup */
    let cleanup = new AbortController();
    window.addEventListener('beforeunload', this.handleUnload, cleanup)

    /* tear down */
    registerDestructor(this, () => cleanup.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

2 participants