Typed events store using standard schema
npm install @stephansama/typed-events



Typed events store using standard schema
##### Table of contents
Open Table of contents
- Installation
- Usage
- createEvent
- createBroadcastChannel
- React
- References
``sh`
pnpm install @stephansama/typed-events
`javascript`
import * as z from "zod";
create a typed CustomEvent
using a standard-schema compatible validator
`javascript
import { createEvent } from "@stephansama/typed-events";
export const customAnimationEvent = createEvent(
"custom-animation-event",
z.object({
x: z.number(),
y: z.number(),
}),
);
`
somewhere in your codebase
`javascript
export function listenForAnimationEvent() {
const item = document.getElementById("item");
const cleanup = customAnimationEvent.listen((event) => {
item.style.x = event.data.x;
item.style.y = event.data.y;
});
return () => cleanup();
}
`
somewhere else in your codebase
`javascript
export function dispatchEvent() {
const x = document.getElementById("x");
const y = document.getElementById("y");
const button = document.getElementById("button");
button.addEventListener("click", () => {
customAnimationEvent.dispatch({
x: +x.innerText,
y: +y.innerText,
});
});
}
`
create a typed BroadcastChannel
using a standard-schema compatible validator
`javascript
import { createBroadcastChannel } from "@stephansama/typed-events";
export const channel = createBroadcastChannel("broadcaster", {
reset: z.object({}),
update: z.object({ value: z.number() }),
});
`
somewhere in your codebase
`javascript
export function listenForChannelMessage() {
const value = document.getElementById("value");
const cleanup = channel.listen("update", (message) => {
value.textContent = message.data.value;
});
return () => cleanup();
}
`
somewhere else in your codebase
`javascript
export function dispatchChannelMessage() {
const button = document.getElementById("button");
button.addEventListener("click", () => {
channel.dispatch("update", {
value: Math.floor(Math.random() * 100),
});
});
}
`
you can use useListener or useListeners to automatically register and cleanup typed event listeners
`javascript
import { createBroadcastEvent } from "@stephansama/typed-events";
import { useListeners } from "../dist/react.cjs";
const broadcastEvent = createBroadcastEvent("react-example", {
first: z.object({}),
second: z.object({ payload: z.number() }),
});
export function ExampleComponent() {
useListeners(broadcastEvent, {
first: () => console.info("first event happened"),
second: ({ data }) => console.info(data.payload),
});
return; // more jsx...
}
``
- BroadcastChannel message event
- BroadcastChannel
- CustomEvent
- MessageEvent
- Window message event
- standardschema