Created
October 14, 2018 02:07
-
-
Save cyan33/468d1e823ccea1fc9b1cbf3a97c0ec2a to your computer and use it in GitHub Desktop.
a simple observer pattern implemented 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