It’s time for a native EventEmitter

Every developer working with javascript has used events hundreds of times. More like thousands. Or millions. Events are the base for UI interaction on the web, and with the popularity of Node.JS and evented frameworks before it, are now a staple in the backend too. If you have a written a decently-sized web site or app in the past years, chances are you’ve used a custom event emitter or the observer pattern in your code many times.

Event-driven architectures are, in my opinion, the most natural way to deal with async code. They free you from cross-referencing objects and methods all over, allowing for really decoupled modules, that don’t need to know details about other parts of the application. As soon as your code starts to grow and you have to handle UI events, XHR requests, dynamic asset loading, you either

            enter
                callback
                     hell,
                         make an entangled chain of method references, or do the sane thing: resort to events.

The proof is in the massive number of event emitter implementations; Backbone has its own, as does Spine, jQuery (it can handle object events too) and most other client frameworks/libraries:

(links point to code)

And of course, a million stand-alone implementations:

Each of these has a slightly different opinion on how things should work, but EventEmitter2 is arguably the canonical implementation - it’s the most complete, battle-hardened and the base for node.js’s EventEmitter.

In the end, they all implement a simple three-method API: addListener, removeListener and trigger. In fact, most of them are functionally equivalent and just differ on method naming: *bind add listen on*, *unbind remove off* and *trigger fire dispatch emit*.

(I have to say I’m not very fond of the on/off naming convention. “on” was used as a preposition in the original DOM events like onclick, not as an adverb (being “on/off”). That’s annoying.)

We should end this mess and have EventEmitter as a native object. What do you think?