Skip to content

Instantly share code, notes, and snippets.

@itsdouges
Created October 21, 2018 22:06
Show Gist options
  • Select an option

  • Save itsdouges/10d3f3a6a19242185594f723f1aa844b to your computer and use it in GitHub Desktop.

Select an option

Save itsdouges/10d3f3a6a19242185594f723f1aa844b to your computer and use it in GitHub Desktop.

Revisions

  1. @Madou Madou created this gist Oct 21, 2018.
    20 changes: 20 additions & 0 deletions listen.tsx
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,20 @@
    export const listenTo = <K extends keyof DocumentEventMap>(
    type: K | K[],
    listener: (this: Document, ev: DocumentEventMap[K]) => any,
    options?: boolean | AddEventListenerOptions
    ) => {
    if (Array.isArray(type)) {
    type.forEach(typ => {
    document.addEventListener(typ, listener, options);
    });

    return () => {
    type.forEach(typ => {
    document.removeEventListener(typ, listener, options);
    });
    };
    } else {
    document.addEventListener(type, listener, options);
    return () => document.removeEventListener(type, listener, options);
    }
    };