Skip to content

Instantly share code, notes, and snippets.

@Komock
Last active September 11, 2019 20:36
Show Gist options
  • Save Komock/f8b3be2de6f81ac86047a98cee828652 to your computer and use it in GitHub Desktop.
Save Komock/f8b3be2de6f81ac86047a98cee828652 to your computer and use it in GitHub Desktop.
Simple ES6 Observer Class
class Observer {
subscribe(subscriber) {
this.subscribers.push(subscriber);
}
publish(event, data) {
let query = this.subscribers.filter(subscriber => subscriber.event === event);
if (query.length) query.forEach(subscriber => subscriber.action(data));
}
constructor() {
this.subscribers = [];
}
}
// Test
const obs = new Observer();
obs.subscribe({
event: 'event 1',
action: function(data) {
console.log('event 1', data);
}
});
obs.subscribe({
event: 'event 2',
action: function(data) {
console.log('event 2', data);
}
});
setTimeout(() => {
obs.publish('event 1', 'Goodbuy');
}, 2000);
setTimeout(() => {
obs.publish('event 2', 'world');
}, 5000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment