A shop page has a cart widget, a header badge and an analytics script. When an item is added, all three must hear about it, but the code that adds the item should not import any of them. A publish and subscribe hub decouples them: code publishes a message on a topic, and whoever subscribed to that topic receives it. Each subscriber holds a small function that ends its own subscription.
functioncreatePubSub() // returns { subscribe, publish, subscriberCount }subscribe(topic, handler) // returns unsubscribe()publish(topic, data) // returns the number of handlers calledsubscriberCount(topic) // returns a number
topic: any string. The topic "*" means "every topic".
publish(topic, data) calls each handler of topic with data and topic, in the order they subscribed.
Topics are separate, and no name is special: "constructor" has no subscribers until one subscribes.
publish returns how many handlers it called (0 when nobody listens).
subscribe returns an unsubscribe function that ends that one subscription. Calling it again does nothing.
The same handler subscribed twice runs twice, and each unsubscribe ends only its own subscription.
Handlers subscribed to "*" receive every message, with its real topic, after the topic's own handlers. Publishing to "*" itself calls each of them once.
A handler that throws does not stop the others: publish catches the error, reports it with reportError(error), and goes on. The count includes that handler.
A handler subscribed during a publish first runs on the next one.
subscribe throws a TypeError when handler is not a function, and stores nothing.