A plain event emitter matches topics by string equality: subscribe to "user.login", get "user.login" events. Real message buses — MQTT, Redis keyspace notifications, analytics pipelines — go further with hierarchical topics and wildcards, so one subscription can catch a whole family of events. Subscribe to user.* and you hear every direct action; subscribe to user.** and you hear the entire subtree.
Implement pubsubWildcard(), returning { on, emit, off } where dotted topics support two wildcards: * for exactly one segment and ** for the rest.
function pubsubWildcard() {
return {
on, // (pattern, handler) => unsubscribe
emit, // (topic, payload) => void
off, // (pattern, handler) => void
};
}
const bus = pubsubWildcard();
bus.on('user.*', (payload, topic) => console.log(topic, payload));
bus.emit('user.login', { id: 1 }); // matches -> "user.login" {id:1}
bus.emit('user.logout', { id: 1 }); // matches -> "user.logout" {id:1}
bus.emit('user.login.ok', {}); // NO match — * is one segment only
bus.on('user.**', () => {});
bus.emit('user'); // matches (** allows zero remaining)
bus.emit('user.login.ok', {}); // matches (** allows any depth)
user.login.success is three levels. Match segment by segment.* = exactly one segment — user.* matches user.login but not user or user.login.ok. It may appear anywhere, including the middle (a.*.c).** = the rest — matches zero or more remaining segments, and must be the final segment.emit can hit several subscribers (exact and wildcard); each handler is called as handler(payload, topic). Both on's return value and off can unsubscribe.