Skip to content

Instantly share code, notes, and snippets.

@nishanbajracharya
Last active June 11, 2020 08:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nishanbajracharya/7979d5c2d41eaa3c556d95ce762cda9d to your computer and use it in GitHub Desktop.
Save nishanbajracharya/7979d5c2d41eaa3c556d95ce762cda9d to your computer and use it in GitHub Desktop.
Simple observer pattern with example
const observer = new Observer();
// Returns a function which, when called, unsubscribes from the observer.
const unsubscribe = observer.subscribe(data => {
console.log("SingleSubscribe", data);
});
const subscriberA = data => console.log("A", data);
const subscriberB = data => console.log("B", data);
// Returns an array of unsubscribe functions
observer.subscribe([subscriberA, subscriberB]);
observer.set(10);
// To unsubscribe the observer
// unsubscribe()
class Observer {
constructor(state) {
this.state = state;
this.subscribers = [];
}
get() {
return this.state;
}
set(state) {
this.state = state;
this.broadcast(state);
}
subscribeMany(fnArray = []) {
return fnArray.map(fn => this.subscribe(fn));
}
subscribe(fn) {
if (Array.isArray(fn)) {
return this.subscribeMany(fn);
}
this.subscribers.push(fn);
return () =>
(this.subscribers = this.subscribers.filter(
subscriber => subscriber !== fn
));
}
broadcast(data) {
this.subscribers.forEach(subscriber => subscriber(data));
return data;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment