Skip to content

Instantly share code, notes, and snippets.

@JayKan
Created January 4, 2019 11:46
Show Gist options
  • Select an option

  • Save JayKan/0983a0f7b9f3e5bd9a742fb7e99ce1a4 to your computer and use it in GitHub Desktop.

Select an option

Save JayKan/0983a0f7b9f3e5bd9a742fb7e99ce1a4 to your computer and use it in GitHub Desktop.
A simple observer implementation in JavaScript
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