Created
January 3, 2022 21:20
-
-
Save franciscojsc/02ddf5586760bffb6a1e7b802e46a080 to your computer and use it in GitHub Desktop.
Observer pattern in JavaScript
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
| /** | |
| * Subject or Observable | |
| */ | |
| function Observable() { | |
| this.observers = []; | |
| } | |
| /** | |
| * Add observer to observable | |
| * @param {object} observer | |
| */ | |
| Observable.prototype.subcribe = function (observer) { | |
| this.observers.push(observer); | |
| }; | |
| /** | |
| * Remove observer from observable | |
| * @param {object} observer | |
| */ | |
| Observable.prototype.unsubcribe = function (observer) { | |
| this.observers = this.observers.filter(function (obs) { | |
| return obs !== observer; | |
| }); | |
| }; | |
| /** | |
| * Notify observers | |
| * @param {any} data | |
| */ | |
| Observable.prototype.notify = function (data) { | |
| this.observers.forEach(function (observer) { | |
| observer.update(data); | |
| }); | |
| }; | |
| /** | |
| * Listener or Observer | |
| */ | |
| function Observer() { | |
| this.update = function (data) {}; | |
| } | |
| // ------------------------------------------------------------ | |
| const observer1 = new Observer(); | |
| observer1.update = function (data) { | |
| console.log('observer1: ' + data); | |
| }; | |
| const observer2 = new Observer(); | |
| observer2.update = function (data) { | |
| console.log('observer2: ' + data); | |
| }; | |
| const observer3 = new Observer(); | |
| observer3.update = function (data) { | |
| console.log('observer3: ' + data); | |
| }; | |
| const observable = new Observable(); | |
| observable.subcribe(observer1); | |
| observable.subcribe(observer2); | |
| observable.subcribe(observer3); | |
| observable.notify('hello'); | |
| observable.unsubcribe(observer2); | |
| observable.notify('hello'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment