Last active
November 15, 2020 21:09
-
-
Save jremi/6366d38df7ce571b236c337e0b687565 to your computer and use it in GitHub Desktop.
simple es6 style subject/observer attach/detach
This file contains 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
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