Skip to content

Commit

Permalink
Add doc
Browse files Browse the repository at this point in the history
  • Loading branch information
willybrauner committed Aug 31, 2023
1 parent 23b6360 commit ad252c6
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 19 deletions.
12 changes: 0 additions & 12 deletions src/dom/getCssVariable.ts

This file was deleted.

52 changes: 45 additions & 7 deletions src/dom/listener.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,26 @@
/**
* Listen to an event on an obj
*
* ex:
* const unlisten = listen(window, "resize", () => {})
*
* unlisten()
*
* @param obj
* @param event
* @param callback
* @param options
*/

export function listen<K extends keyof (HTMLElementEventMap | DocumentEventMap | WindowEventMap)>(
export function listen<
K extends keyof (HTMLElementEventMap | DocumentEventMap | WindowEventMap),
>(
obj: HTMLElement | Window | Document,
event: (K | string) | (K | string)[],
callback: (event: (HTMLElementEventMap | DocumentEventMap | WindowEventMap)[K]) => any,
options?: boolean | AddEventListenerOptions
callback: (
event: (HTMLElementEventMap | DocumentEventMap | WindowEventMap)[K],
) => any,
options?: boolean | AddEventListenerOptions,
): () => void {
if (typeof event === "string") event = [event]
for (let name of event) obj.addEventListener(name, callback, options)
Expand All @@ -19,13 +29,27 @@ export function listen<K extends keyof (HTMLElementEventMap | DocumentEventMap |
}
}

/**
* Listen to an event on an obj, and remove the listener after the first call
*
* ex:
*
* listenOnce(window, "resize", () => {})
*
* @param obj
* @param event
* @param callback
* @param options
*/
export function listenOnce<
K extends keyof (HTMLElementEventMap | DocumentEventMap | WindowEventMap)
K extends keyof (HTMLElementEventMap | DocumentEventMap | WindowEventMap),
>(
obj: HTMLElement | Window | Document,
event: (K | string) | (K | string)[],
callback: (event: (HTMLElementEventMap | DocumentEventMap | WindowEventMap)[K]) => any,
options?: boolean | AddEventListenerOptions
callback: (
event: (HTMLElementEventMap | DocumentEventMap | WindowEventMap)[K],
) => any,
options?: boolean | AddEventListenerOptions,
): () => void {
const unlisten = listen(
obj,
Expand All @@ -34,11 +58,25 @@ export function listenOnce<
unlisten()
callback(event)
},
options
options,
)
return unlisten
}

/**
* Compose listeners
*
* ex:
*
* const unlisten = listenCompose(
* listen(window, "resize", () => {})
* listen(window, "scroll", () => {})
* )
*
* unlisten()
*
* @param listeners
*/
export function listenCompose(...listeners: (() => void)[]): () => void {
return () => {
for (let listener of listeners) listener()
Expand Down

0 comments on commit ad252c6

Please sign in to comment.