Last active
June 11, 2020 08:31
-
-
Save nishanbajracharya/7979d5c2d41eaa3c556d95ce762cda9d to your computer and use it in GitHub Desktop.
Simple observer pattern with example
This file contains 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
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() |
This file contains 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
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