Created
October 24, 2016 17:12
-
-
Save raduGaspar/5ce3101faa8c26f10b380167c54d91db to your computer and use it in GitHub Desktop.
This file contains 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
let pubSubInstance; | |
const subjects = {}; | |
const hOP = subjects.hasOwnProperty; | |
class PubSub { | |
constructor() { | |
if(!pubSubInstance) { | |
console.log('EventDispatcher instance created'); | |
pubSubInstance = this; | |
} | |
return pubSubInstance; | |
} | |
on(topic, callback) { | |
if(!hOP.call(subjects, topic)) { | |
subjects[topic] = []; | |
} | |
let index = subjects[topic].push(callback) - 1; | |
return { | |
remove: () => { | |
delete subjects[topic][index]; | |
} | |
} | |
} | |
trigger(topic, data) { | |
if(!hOP.call(subjects, topic)) return; | |
subjects[topic].forEach((entry) => { | |
if(entry) { | |
entry(data !== undefined ? data : {}); | |
} | |
}); | |
} | |
}; | |
export default class EventDispatcher { | |
constructor() { | |
pubSubInstance = new PubSub(); | |
} | |
on() { | |
pubSubInstance.on.call(pubSubInstance, ...arguments); | |
} | |
trigger() { | |
pubSubInstance.trigger.call(pubSubInstance, ...arguments); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment