Skip to content

Instantly share code, notes, and snippets.

@amundo
Created November 2, 2014 20:23
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 amundo/2c52b5f914167eb68fa5 to your computer and use it in GitHub Desktop.
Save amundo/2c52b5f914167eb68fa5 to your computer and use it in GitHub Desktop.
Do we really need an event emitter?

A ton of libraries out there model “event emitting”:

https://github.com/HenrikJoreteg/wildemitter

These libraries all allow us to create some sort of emitter object on which we can register and trigger custom events.

I’m not sure I get it.

It seems that everyone is shoving this emitter into the global namespace (if it’s used all over an app, no big whoop). So if that’s the case, what do we need an emitter for at all? We can just run addEventListener and dispatchEvent wherever we need to, and those events will be attached to window. (I’m talking browser here, I don’t speak node.)

So the library above wants:

var emitter = new WildEmitter()

Then we can do stuff like:

emitter.on('abc', function(){ console.log('emitter detected the event abc') })

And to trigger that event, we “emit” it… on the emitter (I find the term “emit” not terribly intuitive, incidentally):

emitter.emit('abc')

And sure enough, the log message shows up.

So from wherever in our app, we call these .emit('someevent') things when something another part of the app might want to notice them.

A library-less approach

The DOM gives us the methods addEventListener() and the rarely-used dispatchEvent(). Usually you call them on a reference to a DOM node:

var p = document.querySelector('button');
button.addEventListener('click', function(event){ /* some stuff */ })

But, you can just as well call them “globally”:

addEventListener('click', function(event){ /* some stuff */ })

This is, of course, equivalent to:

window.addEventListener('click', function(event){ /* some stuff */ })

So picture an app like this:

<input><button>+</button>
<ul></ul>

<script>
var Vocab = function(){
  var self = this;
  this.words = [];
  this.add = function(word){
     self.words.push(word);
     dispatchEvent(new CustomEvent('addToVocab', { detail: word } ))
  }
}

var VocabView = function(){
  var el = document.querySelector("ul");
  this.render = function(){
    
  }
}

var vocab = new Vocab();
var vocabView = new VocabView();


addEventListener('addToVocab', )

</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment