Created
December 24, 2021 13:37
-
-
Save sagittaracc/91e240bd91c8947b58f93641c507fa38 to your computer and use it in GitHub Desktop.
Observer pattern in javascript
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 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