Last active
May 18, 2020 21:31
-
-
Save SheepTester/d85a3fe4d9b30c2e429651801aed3650 to your computer and use it in GitHub Desktop.
Using for await for listening to events; inspired by Deno's http module
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export async function * on (target, ...events) { | |
| const nextPromises = [] | |
| let onFire | |
| function addNextPromise () { | |
| addNextPromise.push(new Promise(resolve => (onFire = resolve))) | |
| } | |
| addNextPromise() | |
| function listener (event) { | |
| onFire(event) | |
| addNextPromise() | |
| } | |
| for (const event of events) { | |
| target.addEventListener(event, listener) | |
| } | |
| while (true) { | |
| yield await new Promise(resolve => (onFire = resolve)) | |
| } | |
| } | |
| export function once (target, event) { | |
| return new Promise(resolve => { | |
| target.addEventListener(event, resolve, { once: true }) | |
| }) | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { on, once } from './event-utils.js' | |
| await once(document, 'DOMContentLoaded') | |
| for await (const event of on(document.body, 'pointerdown', 'pointermove', 'pointerup')) { | |
| switch (event.type) { | |
| case 'pointerdown': { | |
| // ... | |
| break | |
| } | |
| case 'pointermove': { | |
| // ... | |
| break | |
| } | |
| case 'pointerup': { | |
| // ... | |
| break | |
| } | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is flawed since it'll skip events if you
awaitinside the for loop oof