Created
September 15, 2017 21:48
-
-
Save trevorhreed/441128278f8d5b099620c23283a22ed8 to your computer and use it in GitHub Desktop.
Simple event bus
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
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