liveBook · Manning

Event bus

As explained in Web Components in Action

An event bus is a messaging pattern that routes published events between decoupled parts of an application.

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

How Web Components in Action covers it

How deep it goes
Defines subscription and dispatch, demonstrates CustomEvent payloads, and stops short of rewriting the entire application.
Examples
Uses a distant color picker target and a workout player receiving playlist time updates.
What it assumes
Assumes familiarity with DOM events and Web Components while introducing centralized event routing as a lightweight alternative to frameworks.
What you can do after
Build it from scratch with DOM-like subscription and dispatch methods for application-wide CustomEvent communication.
How it connects
Connects DOM events, event bubbling, Custom Events, Web Components, and centralized data models.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Web Components in Action. The section links point to the parts of the book it draws on.