An event bus routes messages between application parts when DOM bubbling follows the wrong path. It is useful when one component must notify a distant component without depending on their DOM hierarchy or adding a larger framework. section 1.3 section 14.6
A minimal event bus keeps the familiar DOM event shape:
- Subscribe with addEventListener(type, callback), storing the event type and callback. section 14.6
- Publish with dispatchEvent(event), invoking callbacks whose registered type matches the event type. section 14.6
- Reuse CustomEvent objects and their detail payloads, so event-bus usage remains consistent with DOM events. section 14.6
Workout player updates
A workout plan data model creates an onPlaylistTimeUpdate CustomEvent containing the current exercise, whether it changed, its index, and elapsed time. The workout player subscribes through EventBus and updates its label, background image, and timer. Playback logic can therefore notify the player without bubbling events through the page or exposing a child-component API. section 14.6
Listing 14.16. A simple event bus
export default {
addEventListener(type, cb) { #1
if (!this._listeners) {
this._listeners = [];
}
let listener = { type: type, callback: cb };
this._listeners.push(listener); #2
return listener;
},
dispatchEvent(ce) {
this._listeners.forEach( function(l) { #3
if (ce.type === l.type) {
l.callback.apply(this, [ce]); #4
}
});
}
}
Use the simple event-bus listing to inspect subscription storage, event-type matching, callback invocation, and the DOM-like method names. section 14.6
