Event is a little component I’m using to listen, remove, filter or delegate events in some of my projects (see maple or event-plugin). Nothing really new you may say, well it’s not entirely true


Event is a cross-browser event binder. Here’s below how to add an event listener:

var events = require('event');

events(document.body, 'click', function(ev, target) {
  //do something

and also remove one:

events.off(document.body,'click', fn);

IE8 events don’t have a target properties (they use srcElement instead). This is why Event pass the target node as the second argument of handler’s callback.

Note: Try not to use the keyword event with chrome (reserved keyword inside an event handler).

Event delegation

Spreading event handlers accross your application might take a long time especially on mobile devices. This is one of the reason why it is considered as a good practice to use event delegation.

Event uses query selection to delegate events:

var list = document.querySelector('.list');

//execute fn only when a li element with the class item is clicked

events(list, 'click li.item', fn);

The example above illustrate pretty well how useful event delegation is. Indeed I don’t need to detach or reatach event handlers every time an element in the list is replaced or removed. I just have one event handler in the list element .

I’m kind of proud of how the component handle event delegation. I saw some libraries out there doing the same thing in hundreds of lines. Here’s how I’m doing:

//check if the target node answers the query selector
function matches(el, target, selector) {
  var nodes = el.querySelectorAll(selector);
  return [].slice.call(nodes).indexOf(target) > -1;

I didn’t use matches because it’s not supported by IE8.

Event filtering

I’m pretty sure you ended up doing something as following when you worked with forms input:

input.addEventListener('keypress', function(ev) {
  //execute on enter
  if(ev.keyCode === 13) {
    //do something

Here’s how you can do the same thing with Event:

//execute callback only on enter
events(input, 'keypress > 13', fn);

Lovely right?


The next version of Event will support event keynames:

//execute callback only on enter
events(input, 'enter', fn);

touch events mapping:

//listen touchend events if touch screen
events(list, 'click', fn);

and also event aggregation:

//execute callback on click or keypress enter
events(list, 'click | enter', fn);