Skip to content

Instantly share code, notes, and snippets.

@franciscojsc
Created January 3, 2022 21:20
Show Gist options
  • Select an option

  • Save franciscojsc/02ddf5586760bffb6a1e7b802e46a080 to your computer and use it in GitHub Desktop.

Select an option

Save franciscojsc/02ddf5586760bffb6a1e7b802e46a080 to your computer and use it in GitHub Desktop.
Observer pattern in JavaScript
/**
* Subject or Observable
*/
function Observable() {
this.observers = [];
}
/**
* Add observer to observable
* @param {object} observer
*/
Observable.prototype.subcribe = function (observer) {
this.observers.push(observer);
};
/**
* Remove observer from observable
* @param {object} observer
*/
Observable.prototype.unsubcribe = function (observer) {
this.observers = this.observers.filter(function (obs) {
return obs !== observer;
});
};
/**
* Notify observers
* @param {any} data
*/
Observable.prototype.notify = function (data) {
this.observers.forEach(function (observer) {
observer.update(data);
});
};
/**
* Listener or Observer
*/
function Observer() {
this.update = function (data) {};
}
// ------------------------------------------------------------
const observer1 = new Observer();
observer1.update = function (data) {
console.log('observer1: ' + data);
};
const observer2 = new Observer();
observer2.update = function (data) {
console.log('observer2: ' + data);
};
const observer3 = new Observer();
observer3.update = function (data) {
console.log('observer3: ' + data);
};
const observable = new Observable();
observable.subcribe(observer1);
observable.subcribe(observer2);
observable.subcribe(observer3);
observable.notify('hello');
observable.unsubcribe(observer2);
observable.notify('hello');
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment