Created
April 10, 2021 11:00
-
-
Save JaysonChiang/84a3faa7a2a556667d1f1ee71e9aacf4 to your computer and use it in GitHub Desktop.
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
const subject = { | |
observers: [], | |
subscribe(fn) { | |
this.observers.push(fn) | |
}, | |
notify(arg) { | |
this.observers.forEach(fn => fn(arg)); | |
} | |
} | |
const joe = { | |
update(message) { | |
console.log(`Joe receive ${message}`) | |
}, | |
hiking() { | |
console.log('Joe go hike') | |
} | |
} | |
const jay = { | |
update(message) { | |
console.log(`Jay read ${message}`) | |
} | |
} | |
// -------------- | |
subject.subscribe(joe.update); | |
subject.subscribe(joe.hiking); | |
subject.subscribe(jay.update); | |
subject.notify('news paper'); | |
// => Joe receive news paper | |
// => Joe go hike | |
// => Jay read news paper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment