Skip to content

Instantly share code, notes, and snippets.

@dacanizares
Created October 27, 2019 03:12
Show Gist options
  • Save dacanizares/78d494b3242a36018fdf56f890510895 to your computer and use it in GitHub Desktop.
Save dacanizares/78d494b3242a36018fdf56f890510895 to your computer and use it in GitHub Desktop.
Observer pattern Straightforward implementation
// 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