Skip to content

Instantly share code, notes, and snippets.

@ericorruption
Created October 26, 2017 14:59
Show Gist options
  • Save ericorruption/5524c8fc15db04fd8af5e833bf178ad8 to your computer and use it in GitHub Desktop.
Save ericorruption/5524c8fc15db04fd8af5e833bf178ad8 to your computer and use it in GitHub Desktop.
Observable pattern in js
// define a class
class Observable {
// each instance of the Observer class
// starts with an empty array of things (observers)
// that react to a state change
constructor() {
this.observers = [];
}
// add the ability to subscribe to a new object / DOM element
// essentially, add something to the observers array
subscribe(f) {
this.observers.push(f);
}
// add the ability to unsubscribe from a particular object
// essentially, remove something from the observers array
unsubscribe(f) {
this.observers = this.observers.filter(subscriber => subscriber !== f);
}
// update all subscribed objects / DOM elements
// and pass some data to each of them
notify(data) {
this.observers.forEach(observer => observer(data));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment