Skip to content

Instantly share code, notes, and snippets.

@JaysonChiang
Created April 10, 2021 11:00
Show Gist options
  • Save JaysonChiang/84a3faa7a2a556667d1f1ee71e9aacf4 to your computer and use it in GitHub Desktop.
Save JaysonChiang/84a3faa7a2a556667d1f1ee71e9aacf4 to your computer and use it in GitHub Desktop.
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