Last active
September 11, 2019 20:36
-
-
Save Komock/f8b3be2de6f81ac86047a98cee828652 to your computer and use it in GitHub Desktop.
Simple ES6 Observer Class
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
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