pwd > ninjaPixel/v2/man-drawer/observer-pattern

The observer pattern in JS

Published

The observer pattern is a mechanism that lets you notify multiple subscribers when something happens.

// observable.js

const observers = [];

export default Object.freeze({
  notify: (data) => observers.forEach((observer) => observer(data)),
  subscribe: (func) => observers.push(func),
  unsubscribe: (func) => {
    [...observers].forEach((observer, index) => {
      if (observer === func) {
        observers.splice(index, 1);
      }
    });
  },
});

And this is how something can subscribe to it:

import Observable from "./observable";

function logger(data) {
  console.log(`${Date.now()} ${data}`);
}

Observable.subscribe(logger);

Finally, this is how the subscriber gets notified:

import Observable from "./observable";

document.getElementById("my-button").addEventListener("click", () => {
  Observable.notify("Clicked!"); // Notifies all subscribed observers
});

You could use this pattern for something like o triggering calls to all of your analytics backends. Check out this example on StackBlitz.