ultra-minimal pubsub module written in TypeScript
README.md

pubsub

ultra-minimal pubsub module written in TypeScript

install

pnpm add @rasch/pubsub
# or with bun
bun add @rasch/pubsub

usage

import { publish, subscribe, unsubscribe } from "@rasch/pubsub"
import { welcome, tryagain } from "./fakeCallbackFunctions.js"

subscribe("login", welcome)
subscribe("loginError", tryagain)

if (user.isLoggedIn()) {
  publish("login", user.name)
} else {
  publish("loginError", `Incorrect username "${user.name}" or password!`)
}

unsubscribe("*")

api

subscribe

subscribe :: string -> (...a -> void) -> void

Attach a callback function to an event.

subscribe("event", myFunction)

publish

publish :: (string, ...a) -> void

Run all of the functions attached to an event with the given arguments.

publish("event", arg)
publish("event", arg1, arg2, ...)

unsubscribe

unsubscribe :: (string, ((...a -> void) | undefined)) -> void

Stop listening for events.

// stop listening to a single event callback function
unsubscribe("event", myFunction)

// stop listening for all callback functions on event
unsubscribe("event")

// cancel all subscriptions
unsubscribe("*")