Problem
Decoupled widgets, micro-frontends and cross-tab messaging often communicate through an event bus, and being able to implement the pub/sub pattern in JavaScript is a common frontend interview question.
Implement a class PubSub with:
subscribe(event, callback)registerscallbackforeventand returns a handle object with anunsubscribe()method.publish(event, ...args)invokes every callback currently subscribed toeventwithargs.
Requirements
- Any number of subscribers can listen to the same event;
publishcalls all of them, in subscription order. - Every argument passed to
publishafter the event name is forwarded to each callback. unsubscribe()removes only the subscription it was returned for; other subscribers keep working.- Calling
unsubscribe()more than once must not throw. - Publishing an event with no subscribers is a silent no-op.
- Events are independent: publishing
"login"never triggers"logout"subscribers.
Example
const bus = new PubSub();
const s1 = bus.subscribe("cart:add", (item, qty) => console.log("s1", item, qty));
bus.subscribe("cart:add", (item) => console.log("s2", item));
bus.publish("cart:add", "book", 2);
// s1 book 2
// s2 book
s1.unsubscribe();
s1.unsubscribe(); // no error
bus.publish("cart:add", "pen", 1);
// s2 pen
bus.publish("cart:clear"); // (nothing logged)
Follow-ups
- How would you support wildcard subscriptions such as
"cart:*"? - How would you prevent one throwing subscriber from stopping the others?
- How does this differ from the observer pattern?