Created
August 22, 2017 17:44
-
-
Save fed/7cc26e554ae168c8449ef495593dfc4c to your computer and use it in GitHub Desktop.
Simple observer pattern implementation
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
function Counter() { | |
this.count = 0; | |
this.observers = []; | |
} | |
Counter.prototype.increment = function () { | |
this.count++; | |
this.notify({ count: this.count }); | |
}; | |
Counter.prototype.addObserver = function (observer) { | |
this.observers.push(observer); | |
}; | |
Counter.prototype.notify = function (data) { | |
this.observers.forEach(function (observer) { | |
observer.call(null, data); | |
}); | |
}; | |
// Test | |
const counter = new Counter(); | |
const curious = function (data) { | |
console.log(`hey, count just got updated, now it's ${data.count}`); | |
} | |
counter.addObserver(curious); | |
counter.increment(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment