Skip to content

Instantly share code, notes, and snippets.

@frostney
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frostney/78c9f6ceb70da39f4107 to your computer and use it in GitHub Desktop.
Save frostney/78c9f6ceb70da39f4107 to your computer and use it in GitHub Desktop.
Event Emitter experiment (<160 characters)
// Originally, I wanted to a simple Node.js Event Emitter-style object in less than 150 characters, but it just wouldn't fit
/*
Couple of thoughts
* The name Emitter shouldn't be changed
* `var` is missing, so it's directly bound to `window` and we're saving characters (Yeah for using a JS bad practice to our advantage)
* While `e` as the property isn't really amazing, it's just there to use as little characters as possible
* Obviously, there is no checking if the events really exist
* With ES6, method shorthands and arrow functions it would be considerably less than 150 characters
*/
// ES5 (151 characters):
Emitter={e:{},on:function(e,f){(this.e[e]=this.e[e]||[]).push(f)},off:function(e){this.e[e]=[]},emit:function(e){this.e[e].forEach(function(a){a()})}}
// ES6 (114 characters):
Emitter={e:{},on(e,f){(this.e[e]=this.e[e]||[]).push(f)},off(e){this.e[e]=[]},emit(e){this.e[e].forEach(a=>a())}}
// You can paste this directly in Firefox Developer Edition and it'll work
// Usage
Emitter.on('boom', function() {
console.log('boom');
});
Emitter.emit('boom');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment