Skip to content

Instantly share code, notes, and snippets.

@sagittaracc
Created December 24, 2021 13:37
Show Gist options
  • Save sagittaracc/91e240bd91c8947b58f93641c507fa38 to your computer and use it in GitHub Desktop.
Save sagittaracc/91e240bd91c8947b58f93641c507fa38 to your computer and use it in GitHub Desktop.
Observer pattern in javascript
class Observer {
constructor (name) {
this.name = name
}
subscribe (event) {
event.addObserver(this)
}
notify (event) {
console.log(this.name + ' has been notified that ' + event.name + ' just came out');
}
}
class Event {
constructor (name) {
this.name = name
this.observers = []
}
addObserver (observer) {
this.observers.push(observer)
}
notify () {
this.observers.forEach(observer => observer.notify(this))
}
}
let me = new Observer('sagittaracc')
let event = new Event('new video on pornhub')
me.subscribe(event)
event.notify()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment