Skip to content

Event Dispatcher

Dispatch custom events in the browser.

๐ŸŽฌ Usage

<script>
    import { event_dispatcher } from "@sveu/browser"

    const dispatch = event_dispatcher(element)
</script>

๐Ÿ‘ฉโ€๐Ÿ’ปAPI

๐Ÿ‘ป Arguments

Name Description Type Required
target The element to dispatch the event on HTMLElement | SVGElement | null | undefined Yes

โ†ฉ๏ธ Returns

Name Description Type
dispatch The function to dispatch the event (name: string, value: T) => void

๐Ÿงช Playground

Source Code ๐Ÿ‘€

Source Code
/**
 * Create a function that dispatches a custom event.
 *
 * @param target - The element to dispatch the event on.
 *
 * @returns The function to dispatch the event.
 */
export function event_dispatcher(
    target: HTMLElement | SVGElement | null | undefined
) {
    /**
     * Dispatch a custom event.
     *
     * @param name - The name of the event.
     *
     * @param value - The value to pass to the event.
     *
     */
    function dispatch<T>(name: string, value: T) {
        target?.dispatchEvent(new CustomEvent(name, { detail: value }))
    }

    return dispatch
}

Last update: 2023-03-12