Skip to content

Instantly share code, notes, and snippets.

@0bie
Created August 25, 2017 17:47
Show Gist options
  • Save 0bie/3e495c35a6d8d8b06ee0a24181aaceb4 to your computer and use it in GitHub Desktop.
Save 0bie/3e495c35a6d8d8b06ee0a24181aaceb4 to your computer and use it in GitHub Desktop.
Understanding the observer pattern
// Observer Pattern Notes
// The instance (subject) maintans a collection of objects (observers)
// The instance notifies the objects when changes to the state occur
class Observable {
// each instance starts with an empty array of observers that react to state changes
constructor() {
this.observers = [];
}
// add the ability to subscribe to a new object / DOM element
// i.e add something to the `observers` array
subscribe(param) {
this.observers.push(param);
}
// add the ability to unsubscribe from a particular object
// i.e remove something from the `observers` array
unsubscribe(param) {
this.observers = this.observers.filter((subscriber) => subscriber !== param);
}
// update all subscribed objects / DOM elements & pass some data to each of them
notify(data) {
this.observers.forEach((observer) => observer(data));
}
}
// Use case examples
// DOM references
const input = document.getElementById('jsInput');
const p1 = document.getElementById('jsP1');
const p2 = document.getElementById('jsP2');
const p3 = document.getElementById('jsP3');
// some actions to add to the observers array
const updateP1 = (text) => p1.textContent = text;
const updateP2 = (text) => p2.textContent = text;
const updateP3 = (text) => p3.textContent = text;
// instantiate a new `Observable` class
const headingsObserver = new Observable();
// subscribe to some observers
headingsObserver.subscribe(updateP1);
headingsObserver.subscribe(updateP2);
headingsObserver.subscribe(updateP3);
// notify all observers about new data
input.addEventListener('keyup', (e) => {
headingsObserver.notify(e.target.value);
});
// https://pawelgrzybek.com/the-observer-pattern-in-javascript-explained/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment