This post was originally published on Coding Glamour.

Chances are that if you have a large javascript application that you'll need an EventEmitter at one moment or another because events are great to wire separate modules together without them having to expose implementation details. Too bad that you'll need to pull in dependencies, another library, extra risk, etc. Especially if you're testing some simple scenario or small app that's a lot of boilerplate. Behold: a dependency-less event emitter (1 line of javascript!):

function createEventEmitter() {
  return document.createElement('div');

All DOM elements implement DOM Level 3 events, which you can abuse as a nice event emitter. Great thing is that you get cancelation and bubbling as well. Bad things:
  • It's about 5x times as slow as EventEmitter.js (source), but you can very easily swap out this by EE if required in a later stage.
  • Dispatching events is a bit cumbersome because you need to use this syntax: `new CustomEvent("eventname", { detail: "eventdetail" })`

var ee = document.createElement('div')
ee.addEventListener('awesome', function() { console.log('omg omg omg', e.detail) })
ee.dispatchEvent(new CustomEvent('awesome', { detail: 1337 }))
// omg omg omg, 1337 /* output from the console.log */
// true /* event did not get canceled */