Simple EventEmitter in one line in javascript nl

Door creator1988 op dinsdag 7 januari 2014 15:12 - Reacties (1)
Categorie: Frontend, Views: 8.559

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 */

Volgende: Fix your own smartphone OS 03-'14 Fix your own smartphone OS
Volgende: Simple function logger in JS 01-'14 Simple function logger in JS


Door Tweakers user Gamebuster, dinsdag 18 maart 2014 14:14

*depends on a browser

I like the creativity involved, but I'll stick with NodeJS' event emitter:
Its source is plain JS and capable of running in the browser.

Also, I love JS blogs. Keep them coming!

[Reactie gewijzigd op dinsdag 18 maart 2014 14:16]

Reageren is niet meer mogelijk