Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// This is the object that once its state changes,
// it will notify all the observers.
function Observable() {
this.observersList = [];
}
Observable.prototype.addObserver = function(observer) {
this.observersList.push(observer);
}
Observable.prototype.removeObserver = function (observer) {
var self = this;
this.observersList.forEach(function(el, index) {
if (el === observer) {
self.observersList.splice(index, 1);
}
})
}
Observable.prototype.notify = function(context) {
for (var i = 0; i < this.observersList.length; i++) {
this.observersList[i].update(context);
}
}
// will get notified if any changes happend on Observable
function Observer(name) {
this.name = name;
var self = this;
this.update = function(context) {
console.log(self.name + " is invoked with the context as " + context);
}
}
var observable = new Observable();
var observerA = new Observer("A");
var observerB = new Observer("B");
observable.addObserver(observerA);
observable.addObserver(observerB);
observable.notify("hello");
// should log
// A is invoked with the context as hello
// B is invoked with the context as hello
observable.removeObserver(observerA);
observable.notify("hello");
// should log
// B is invoked with the context as hello
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment