Created
January 4, 2019 11:46
-
-
Save JayKan/0983a0f7b9f3e5bd9a742fb7e99ce1a4 to your computer and use it in GitHub Desktop.
A simple observer implementation in JavaScript
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
| function createObserver(listeners = {}) { | |
| function addListener(eventType, cb) { | |
| if (listeners.hasOwnProperty(eventType)) { | |
| listeners[eventType].push(cb); | |
| } else { | |
| listeners[eventType] = [cb]; | |
| } | |
| return function removeListener() { | |
| const index = listeners[eventType].indexOf(cb); | |
| } | |
| } | |
| function notify(eventType, ev) { | |
| if (listeners[eventType]) { | |
| listeners[eventType].forEach((cb) => { | |
| cb(ev); | |
| }) | |
| } | |
| } | |
| function removeAllListeners() { | |
| listeners = []; | |
| } | |
| return { | |
| addListener, | |
| notify, | |
| removeAllListeners | |
| } | |
| } | |
| const obj = createObserver(); | |
| obj.addListener('fooEvent', (e) => { | |
| console.log(e.name); | |
| }) | |
| obj.notify('fooEvent', { name: 'fooEvent' }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment