Created
November 17, 2017 11:36
-
-
Save herber/f64fc34eab9f762877e62920a0b484bd to your computer and use it in GitHub Desktop.
A simple js emitter
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
const emitter = () => { | |
const listener = {}; | |
const x = {}; | |
x.on = (name, fn) => { | |
if (typeof fn !== 'function' || typeof name !== 'string') { | |
throw new Error('Wrong parameter(s)'); | |
} | |
listener[name] = fn; | |
return (fn) => { | |
delete listener[name]; | |
}; | |
}; | |
x.emit = (name, ...args) => { | |
if (typeof name !== 'string') { | |
throw new Error('Name must be a string'); | |
} | |
if (typeof listener[name] === 'function') { | |
listener[name](...args); | |
} else { | |
throw new Error('Function not registered'); | |
} | |
}; | |
x.off = (name) => { | |
delete listener[name]; | |
}; | |
return x; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment