Skip to content

Instantly share code, notes, and snippets.

@fed
Created August 22, 2017 17:44
Show Gist options
  • Save fed/7cc26e554ae168c8449ef495593dfc4c to your computer and use it in GitHub Desktop.
Save fed/7cc26e554ae168c8449ef495593dfc4c to your computer and use it in GitHub Desktop.
Simple observer pattern implementation
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