Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
exports.RunObserver = () => {
/**
* Subject could be anything, Whatsapp group, Circket feed, news letter
* notification
*/
var Subject = function () {
//List of subscribers
this.observers = [];
return {
//Add subscriber
subscribeObserver: (observer) => {
console.log(this)
this.observers.push(observer);
},
//Remove Subscriber
unsubscribeObserver: (observer) => {
var index = this.observers.indexOf(observer);
if (index > -1) {
this.observers.splice(index, 1);
}
},
//Notify a single suscriber
notifyObserver: (observer) => {
var index = this.observers.indexOf(observer);
if (index > -1) {
this.observers[index].notify(index);
}
},
// Notify all subscribers
notifyAllObservers: () => {
for (var i = 0; i < this.observers.length; i++) {
this.observers[i].notify(i);
};
}
};
};
/**
* Generic observer function
*/
var Observer = function () {
return {
notify: function (index) {
console.log("Observer " + index + " is notified!");
}
}
}
var subject = new Subject();
var observer1 = new Observer(); // User 1
subject.subscribeObserver(observer1);
var observer2 = new Observer(); // User 2
subject.subscribeObserver(observer2);
var observer3 = new Observer(); // User 3
subject.subscribeObserver(observer3);
var observer4 = new Observer(); // User 4
subject.subscribeObserver(observer4);
subject.notifyObserver(observer2); // Observer 2 is notification!
subject.notifyAllObservers(); //Every subscribers will get the notification
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.