Skip to content

Instantly share code, notes, and snippets.

@jremi
Last active November 15, 2020 21:09
Show Gist options
  • Save jremi/6366d38df7ce571b236c337e0b687565 to your computer and use it in GitHub Desktop.
Save jremi/6366d38df7ce571b236c337e0b687565 to your computer and use it in GitHub Desktop.
simple es6 style subject/observer attach/detach
class Subject {
constructor() {
this.observers = [];
}
attach(observer) {
this.observers.push(observer);
}
detach(observer) {
this.observers = this.observers.filter((obs) => obs !== observer);
}
notify() {
this.observers.forEach((obs) => obs.update());
}
}
class Observer {
constructor(fn) {
this.fn = fn;
}
update() {
this.fn();
}
}
const subject = new Subject();
const observer1 = new Observer(() => {
console.log("Fired observer1");
});
const observer2 = new Observer(() => {
console.log("Fired observer2");
});
const observer3 = new Observer(() => {
console.log("Fired observer3");
});
subject.attach(observer1);
subject.attach(observer2);
subject.attach(observer3);
subject.notify();
subject.detach(observer2);
subject.notify();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment