Created
October 26, 2017 14:59
-
-
Save ericorruption/5524c8fc15db04fd8af5e833bf178ad8 to your computer and use it in GitHub Desktop.
Observable pattern in js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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