EventBus class.subscribe(event, listener) for registering a listener with an event.emit(event, payload) so every listener registered for that event receives the payload.A suitable API shape is:
interface Listener {
onEvent(payload)
}
class EventBus {
subscribe(event, listener)
emit(event, payload)
}
bus = EventBus()
bus.subscribe("door.opened", listenerA)
bus.emit("door.opened", {"room": "lab"})
Output: listenerA receives {"room": "lab"}.
The listener is called because it is registered for "door.opened".
bus = EventBus()
bus.subscribe("job.done", listenerA)
bus.subscribe("job.done", listenerB)
bus.emit("job.done", 42)
Output: listenerA and listenerB each receive 42.
Both subscriptions match the emitted event, so both listeners run.
bus = EventBus()
cancel = bus.subscribe("message", listenerA)
cancel()
bus.emit("message", "hello")
Output: no listener is invoked.
Calling the returned cancellation operation removes listenerA from that event before the emission occurs.
subscribe, emit, and unsubscribe, making sure one event can retain multiple listeners; afterward, consider changing subscribe to return a cancellation callback or a subscription token.