liveBook · Manning

Decoupling

As explained in Secrets of the JavaScript Ninja, Second Edition

A design property in which interacting components know little or nothing about one another's internal details or control flow.

Decoupling lets code signal that something happened without knowing who will respond—or whether anyone will. DOM event handlers demonstrate this: handlers can respond independently to the same event. section 13.3.2

Custom events keep shared code from depending on page-specific callbacks:

  • A global-function approach requires shared code and page code to agree on a function name; custom events let interested code subscribe independently. section 13.3.2
  • Multiple handlers can react independently, and custom events can carry details for listeners. section 13.3.2

An operation signals its progress

An AJAX operation dispatches start and completion events; separate listeners show and hide a spinner, and the start event can include a URL. section 13.3.2

button.addEventListener('click', () => {
  performAjaxOperation();
});

document.addEventListener('ajax-start', e => {
  document.getElementById('whirlyThing').style.display = 'inline-block';
  assert(e.detail.url === 'my-url', 'We can pass in event data');
});

document.addEventListener('ajax-complete', e => {
    document.getElementById('whirlyThing').style.display = 'none';
});

See the listeners that respond to the AJAX events and read data from the start event. section 13.3.2

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Defines loose coupling, contrasts global callbacks, and demonstrates independent handlers and custom-event signaling.
Examples
Demonstrates an AJAX operation whose start and completion events control a spinner and carry URL data.
What it assumes
Assumes familiarity with DOM event listeners while explaining handler registration and event objects.
What you can do after
Apply it via CustomEvent, dispatchEvent, and addEventListener to signal operation state to independent listeners.
How it connects
Connects loose coupling with custom events, DOM events, and event handlers.

Also explained in

Compare how 4 books explain decoupling →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.