Events
A tiny, zero-dependency event bus. Subscribe to a named event, trigger it from anywhere, and clean up a whole namespace of subscriptions in one call. It’s the substrate @mongez/atom uses under the hood for atom lifecycle events — and it’s perfectly usable on its own for any pub/sub flow.
Highlighted features
One global bus, zero deps
Module-level singleton, no provider, no setup. Import events and you’re in.
Namespace-scoped cleanup
Subscribe to users.created, users.deleted, users.updated — then drop them all with events.unsubscribeNamespace(“users”).
Stop-on-false chain
Any handler can short-circuit the chain by returning false. Perfect for cancellable beforeXxx events.
Powers @mongez/atom
Atom lifecycle (atoms.<key>.update, reset, delete) is built on this bus. Same primitive, smaller bundle.
Install
npm install @mongez/eventsyarn add @mongez/eventspnpm add @mongez/eventsZero runtime dependencies.
Quick peek
import events from "@mongez/events";
const sub = events.subscribe("cart.update", cart => { console.log("cart now has", cart.totalQuantity, "items");});
events.trigger("cart.update", { totalQuantity: 3 });
sub.unsubscribe();Subscribe from anywhere, trigger from anywhere, hold the returned EventSubscription and call .unsubscribe() when done.
Mental model
- One global bus instance.
eventsis a module-level singleton. All subscribers share it. - Events are strings with dot-separated segments.
users.created,cart.checkout,atoms.userAtom.update. - Namespaces are event-name prefixes that match at segment boundaries. Cleanup by namespace wipes a whole subtree without touching unrelated events.
- Subscriptions return an object, not an unsubscribe function. Hold the returned
EventSubscriptionand call.unsubscribe()when done.
Where to go next
- Events bus —
subscribe,trigger,unsubscribe, advanced patterns - Namespaces — namespace-scoped cleanup, query helpers
- Recipes — common patterns (auth, cart, atom integration)