Skip to content

Instantly share code, notes, and snippets.

@herber
Created November 17, 2017 11:36
Show Gist options
  • Save herber/f64fc34eab9f762877e62920a0b484bd to your computer and use it in GitHub Desktop.
Save herber/f64fc34eab9f762877e62920a0b484bd to your computer and use it in GitHub Desktop.
A simple js emitter
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