-
-
Save bboy114crew/2151e81897f6b8490b7a2e222508d916 to your computer and use it in GitHub Desktop.
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
// 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