UNPKG

@solid-primitives/event-dispatcher

Version:
26 lines (25 loc) 1.45 kB
import { isServer } from "solid-js/web"; /** * Creates a typed `CustomEvent` dispatcher for emitting events. * @returns dispatcher that will create a DOM custom event (`CustomEvent<T>`) and call the associated event handler * * The dispatcher takes three arguments: * @param eventName the event name in lower camel case. E.g, `customMessage`. When dispatching the event, the dispatcher will look for the "`on`+ upper camel case name in the props (`onCustomMessage`) * @param payload the payload associated to the event. This value is optional, and will be accessible in the `CustomEvent.detail` property * @param options the dispatcherOptions is an object with one property, `cancelable`, which determines whether the created custom event is cancelable (meaning its `preventDefault()` method can be called). This arguments is optional and defaults to `{ cancelable: false }`. */ export function createEventDispatcher(props) { if (isServer) { return () => false; } return function (...args) { const [eventName, detail, { cancelable = false } = {}] = args; const propName = `${"on"}${eventName[0].toUpperCase()}${eventName.slice(1)}`; const handler = props[propName]; if (typeof handler !== "function") return true; const customEvt = new CustomEvent(eventName, { detail, cancelable }); handler(customEvt); return !customEvt.defaultPrevented; }; }