Created
October 17, 2018 12:59
-
-
Save nishanbajracharya/7e3ac9940aa3e28bc057939d9a82e027 to your computer and use it in GitHub Desktop.
Javascript Observer Pattern
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
const observer = new Observer(); | |
const unsubscribe = observer.subscribe(a => console.log(a)); | |
observer.broadcast('1'); | |
unsubscribe(); | |
observer.broadcast('1'); |
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
class Observer { | |
constructor() { | |
this.observers = []; | |
} | |
subscribe(fn) { | |
this.observers.push(fn); | |
return () => this.observers = this.observers.filter(subscriber => subscriber !== fn); | |
} | |
broadcast(data) { | |
this.observers.forEach(subscriber => subscriber(data)); | |
return data; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment