Created
October 27, 2019 03:12
-
-
Save dacanizares/78d494b3242a36018fdf56f890510895 to your computer and use it in GitHub Desktop.
Observer pattern Straightforward implementation
This file contains hidden or 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
// Observer pattern | |
// Straightforward implementation | |
class Notification { | |
constructor() { | |
this.subs = []; | |
} | |
subscribeMe = (subscriptor) => { | |
this.subs.push(subscriptor); | |
console.log("New subscriber ",subscriptor); | |
} | |
notify = (newMessage) => { | |
console.log("An event occured!"); | |
for (let i = 0; i < this.subs.length; ++i) { | |
this.subs[i](newMessage); | |
} | |
} | |
} | |
// We can define multiple functions | |
// that will be subscribed to the | |
// notification mechanism | |
const sayAlert = (msj) => { | |
alert(msj); | |
} | |
const logger = (msj) => { | |
console.log(msj); | |
} | |
// Then glue it all! | |
const notifier = new Notification(); | |
notifier.subscribeMe(sayAlert); | |
notifier.subscribeMe(logger); | |
// And send a notification to all the | |
// subscribers | |
notifier.notify('You had a new message'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment