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

One-time awaitable event listeners #8513

Closed
josephrocca opened this issue Nov 16, 2022 · 4 comments
Closed

One-time awaitable event listeners #8513

josephrocca opened this issue Nov 16, 2022 · 4 comments

Comments

@josephrocca
Copy link

josephrocca commented Nov 16, 2022

Wondering if there has been any discussion around a better "built-in" solution to this sort of requirement?

// An `await`able function that resolves when page visibility changes:
function visibilityChange() {
  return new Promise(resolve => {
    document.addEventListener("visibilitychange", function() {
      resolve(document.visibilityState);
      document.removeEventListener("visibilitychange", arguments.callee);
    });
  });
}

// Use it like this:
await visibilityChange();
console.log(document.visibilityState);

I find myself doing this sort of thing fairly often (for many different types of events - not just visibilitychange) and it feels very "clunky".

@josephrocca
Copy link
Author

Here are some vaguely related discussions, though all existing discussion seems to revolve around loading rather than events more generally.

@Kaiido
Copy link
Member

Kaiido commented Nov 16, 2022

whatwg/dom#1038 maybe?

@jimmywarting
Copy link

You could also do:

function visibilityChange() {
  return new Promise(rs => document.addEventListener('visibilitychange', rs, { once: true }))
}

just maybe i would apply it to a more generic util pattern to some like:

const once = (elm, type) = new Promise(rs => el.addEventListener('visibilitychange', rs, { once: true }))

// and use it as such:
const evt = await once(document, 'visibilitychange')
console.log(document.visibilityState)

I don't particularly see any need for a one-time awaitable event listener. it can already be solved in user land. i think there is other more important features that gets higher priority such as those thing that can't be polyfilled

@annevk
Copy link
Member

annevk commented Oct 11, 2024

Let's duplicate this into the DOM issue. HTML doesn't define Events.

@annevk annevk closed this as not planned Won't fix, can't repro, duplicate, stale Oct 11, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

4 participants