Skip to content

Instantly share code, notes, and snippets.

@bjarneo
Last active September 18, 2017 16:52
Show Gist options
  • Select an option

  • Save bjarneo/e5e89d96f0bbdc8a27d3c5342d92c5ec to your computer and use it in GitHub Desktop.

Select an option

Save bjarneo/e5e89d96f0bbdc8a27d3c5342d92c5ec to your computer and use it in GitHub Desktop.
Event emitter in 11 lines of code
const events = {};
function on(event, callback) {
if (!events[event]) {
events[event] = [];
}
events[event].push(callback);
}
const trigger = (event, data = null) => events[event].forEach(callback => callback(data));
// Usage:
on('cat-names', console.log);
trigger('cat-names', 'furguson');
trigger('cat-names', 'mittens');
trigger('cat-names', 'boots');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment