Skip to content

Instantly share code, notes, and snippets.

@trevorhreed
Created September 15, 2017 21:48
Show Gist options
  • Save trevorhreed/441128278f8d5b099620c23283a22ed8 to your computer and use it in GitHub Desktop.
Save trevorhreed/441128278f8d5b099620c23283a22ed8 to your computer and use it in GitHub Desktop.
Simple event bus
const EventBusFactory = () => {
let repo = {};
return {
add(key, fn){
if(typeof fn !== 'function') throw `Invalid parameter. Second parameter must be a function.`;
if(!repo[key]) repo[key] = [];
if(!repo[key].includes(fn)) repo[key].push(fn);
},
remove(key, fn){
if(!repo[key]) return;
if(!repo[key].includes(fn)) return;
const index = repo[key].indexOf(fn);
if(index !== -1) repo[key].splice(index, 1);
},
trigger(key, data){
if(!repo[key]) return;
repo[key].forEach(fn => fn(data));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment