TypeScript
For plain TypeScript or JavaScript projects, use @busly/js. It has no framework, dependency injection, or RxJS involved, just functions and callbacks.
Installation
pnpm add @busly/js @busly/core @busly/eventsnpm install @busly/js @busly/core @busly/eventsbun add @busly/js @busly/core @busly/eventsTogether, these three packages weigh less than 2 KB in the browser.
The examples on this page use the counterPageEvents group from Define events.
Dispatching events
Self-dispatching group
The most convenient way to send events is createDispatcher, which turns an event group into an object with one function per event:
import { createDispatcher } from '@busly/js';
import { counterPageEvents } from './counter.events';
const counter = createDispatcher(counterPageEvents);
counter.increment();
counter.set(42);
counter.loadSuccess({ count: 42 });The payload types come straight from the group, so counter.set('42') won't compile, and counter.increment() doesn't accept an argument at all.
Each method is a plain closure rather than a class method, so you can destructure it and pass it around without worrying about this:
const { increment } = counter;
button.addEventListener('click', () => increment());Notice the arrow function in that listener. If you passed increment directly, the DOM would call it with the Event object, which would become the payload and fail to clone.
You only need to create a dispatcher once, either at module level or once per component.
Single event
When you already have an event object in hand, perhaps because the creator was picked at runtime, dispatch sends it directly:
import { dispatch } from '@busly/js';
dispatch(counterPageEvents.set(42));Source
Both createDispatcher and dispatch accept options. The source option labels the sender, and every receiver sees it as event.source:
const counter = createDispatcher(counterPageEvents, { source: 'shell' });
dispatch(counterPageEvents.set(42), { source: 'shell' });If you don't set it, the source is 'busly-js'.
Errors
If a payload can't be cloned, the dispatch throws a DataCloneError right away, and the event isn't delivered anywhere:
counter.loadSuccess({ count: 1, refresh: () => {} } as any); // throws DataCloneErrorListening to events
To listen, create a receiver and register handlers on it:
import { createReceiver } from '@busly/js';
const receiver = createReceiver();
const off = receiver.on(counterPageEvents.set, ({ payload, source }) => {
console.log(`${source} set count to ${payload}`);
});
off(); // removes this handler
receiver.dispose(); // removes every handler of this receiverThe handler receives the event together with its envelope metadata (type, payload, source, ts, and v), all typed from the creator.
Several events, one handler
To handle more than one event with the same function, pass an array of creators. TypeScript narrows the event to a union, so you can branch on its type:
receiver.on([counterPageEvents.increment, counterPageEvents.set], (event) => {
if (event.type === counterPageEvents.set.type) {
state.count = event.payload;
} else {
state.count += 1;
}
});Passing an empty array throws an error, since there would be nothing to listen to.
Cleanup
Every call to on or lazy returns its own unsubscribe function, and calling it more than once is harmless. If you register the same handler twice, you get two independent subscriptions, each with its own unsubscribe.
dispose() removes all the handlers that receiver registered, and nothing else. Other receivers keep working, and the disposed receiver can still be used afterwards.
Because receivers are cheap, a good habit is to create one per component, feature, or lifecycle, and dispose it when that scope ends:
class CounterWidget {
readonly #receiver = createReceiver();
readonly #counter = createDispatcher(counterPageEvents, { source: 'counter-widget' });
mount(el: HTMLElement) {
this.#receiver.on(counterPageEvents.set, ({ payload }) => {
el.textContent = String(payload);
});
el.addEventListener('click', () => this.#counter.increment());
}
unmount() {
this.#receiver.dispose();
}
}Errors in handlers
If a handler throws, the other handlers still run. The error isn't swallowed, though: it's re-thrown in a microtask, so it still reaches window.onerror and whatever error tracking you have in place.
The on / lazy event handlers
Receivers expose the two cohorts described in on and lazy. Use on to apply state, and lazy for side effects that need to read that state.
What makes this work in @busly/js is that the order holds across receivers, not just within one. Every receiver in the application shares a single subscription per event type, and that subscription runs all the on handlers before any of the lazy ones. So your effects and your state can live in completely separate modules:
const state = { count: 0 };
// effects module, subscribed first
const effects = createReceiver();
effects.lazy(counterPageEvents.set, async () => {
await fetch('/api/count', { method: 'PUT', body: JSON.stringify(state.count) });
});
// state module
const store = createReceiver();
store.on(counterPageEvents.set, ({ payload }) => {
state.count = payload;
});
createDispatcher(counterPageEvents).set(42);
// on: state.count = 42 → lazy: PUT 42There are a few things to keep in mind. Keep your on handlers synchronous, because a state write that happens after an await will land after the lazy handlers have run.
Handlers added while an event is being delivered wait for the next event, and handlers removed during delivery are skipped.
Dispatching from inside a handler is perfectly fine. The new event arrives once the current one has gone through both cohorts.
Lastly, the order only spans one copy of @busly/js. Microfrontends that bundle their own copy order their handlers independently.
Dispatch-only state
Since the sender also receives its own events, your actions can dispatch an event instead of writing state directly. The on handler then becomes the single path that updates state in every context, including this one:
const counter = createDispatcher(counterPageEvents);
export const actions = {
set: (n: number) => counter.set(n), // no direct write
};
createReceiver().on(counterPageEvents.set, ({ payload }) => {
state.count = payload; // runs here and in every other context
});The trade-off is that local state updates one microtask later than it would with a direct write.
Server-side rendering
On the server, dispatching sends nothing, and on and lazy return a function that does nothing. Receivers and dispatchers created with createDispatcher check the environment once, when they're created, while dispatch checks it on every call. If the detection gets it wrong for your setup, you can override it:
createReceiver({ server: false });
createDispatcher(counterPageEvents, { server: true });
dispatch(counterPageEvents.increment(), { server: false });Electron renderers have a window, so they count as browser contexts, and so do workers.