Passing Objects into addEventListener Instead of Functions

I was reviewing the browser event stack the other day and was reminded of a rarely used feature of addEventListener that allows developers to autobind the execution context object, instead of requiring a call to bind or using a library, that is worth sharing, if you weren’t already aware.

How do it…

Typically, when attaching an event, we write:

var myObj = {
    handleEvent: function (evt) {
        // 'this' will be scoped to the element, instead of myObj.
    }
};
document.getElementById('<MY_ID>').addEventListener(
    'click', myObj.handleEvent);

However, addEventListener also supports passing an object as the second argument, as long as the object defines handleEvent:

var myObj = {
    handleEvent: function (evt) {
        // 'this' will be scoped to myObj.
    }
};
document.getElementById('<MY_ID>').addEventListener('click', myObj);

The event is removed in the same fashion:

document.getElementById('<MY_ID>').removeEventListener('click', myObj);

For a full-fledged implementation, I would do something like this:

var myObj = {
    keyPressEvent: function (evt) {
        // handle key only events
    },
    clickEvent: function (evt) {
        // handle click only events
    },
    handleEvent: function (evt) {
        switch (evt.type) {
            case 'click':
                this.clickEvent(evt);
                break;
            case 'keypress':
                this.keyPressEvent(evt);
                break;
        }
    },
    init: function() {
        var el = document.getElementById('<MY_ID>');
        el.addEventListener('click', myObj);
        el.addEventListener('keypress', myObj);
    }
};
myObj.init();

How it works…

The spec for addEventListener allows developers to pass, as the second argument, either a function or an object with a function named handleEvent attached to it. The rest of the signature is identical between the two implementations. If an object is passed, then the execution context of the callback function will be set to the object, instead of the triggering element, which is usually the desired behavior.

The biggest advantage here is writing less, clearer code that does exactly what you want. It is supported by all modern browsers and has been around since addEventListener was added. Unfortunately, the first modern browser produced by Microsoft was IE9, so if you have to support IE < 9, then you’ll need a polyfill[1].

One other advantage to this style of event management, is the implementation of the event specific callbacks can change or be overwritten without the need to remove and/or reattach event listeners.

References

  1. addEventListener, handleEvent and passing objects - has a decent IE polyfill
  2. An alternative way to addEventListener

Running Android Tests on a Device or Emulator

I have not been doing much web development lately, so its been difficult to come with interesting topics. However, I have been doing a lot of android development and since many engineers have to work cross discipline, I think an android article be relevant. This article will discuss how to run unit tests against your android code, directly on the android device or emulator.

Getting ready

You will need to install the

Cherry-Picking for Fun and Profit

In Git, it is often useful to merge one specific commit from one branch into another. Frequently this happens when Using Git Interactive Rebase With Feature Branches, as you develop in the branch, you realize that one or more of your commits should be added to master right away, but not all the CLs. Enter git cherry-pick <changelist hash> for the win! The cherry pick command allows you to merge one CL from a ...

Gaming Engine - Snake Demo v2

Last week I was busy at GDC and have not had time to put together a detailed article, so in the spirit of GDC, I thought I would share the latest iteration of my HTML5 gaming engine (still very rough). There has been a lot of progress around the Game class to support stages (or levels) and a score board to track the player’s score. The stages are demoed by a new version ...

Use && Instead of Semicolon to Separate Commands

Today’s article will be short and will cover a bash topic that frustrates me to no end. Please don’t use ; to separate commands, when you mean &&. There is an important difference between the two and many developers never realize that they want to be using && in their scripts.

How do it…

Here is a common oneliner that you might use to compile a package:
 ./configure ; make ; make ...

Using Promises to Cache Static AJAX JSON Data

This article showcases a useful caching strategy for static data that is fetch via AJAX. We will use jQuery to setup a promise and cache the data in the localStorage for subsequent page loads or data loads.

Getting ready

A modern web browser supporting localStorage and JSON. Also, a basic understanding of promises[2] is helpful.

How do it…

Here is the code:
 (function($) { var oKeyDeferredMap = {}; function fnReadData(sKey) ...

Connecting to Github and EC2 Through a Proxy on Port 80 or 443

Today we’ll cover how to connect to github and EC2 through a draconian proxy allowing only port 80 and 443. Github uses SSH, so like EC2 it can be connected to using SSH tunnelling. This article is based on a blog post by tachang[1], which needed some additional explanation and changes to work behind my proxy. I will be explaining how to connect on a unix-based machine, but these settings should also work on ...

Introducing Gaming Engine - Snake Demo v1

In my not so copious spare time over the past few months, I’ve been working on a game engine to power two dimensional board-based games. The engine has a long way to go, but I have reach the first demo milestone and wanted to share it with you. Here is a basic version the snake game written using the game engine. It illustrates a working main thread, responsiveness to keyboard commands, interaction between a ...

jQuery Function for Change Event and Delayed Keydown Event

In my experience, it is rare to assign only a change event to a text input, as any callback that would be executed for the change event should also be called on a key event as well, but with a slight delay (think how an autocomplete shows results as you type). This is a common pattern and I was surprised to not immediately find a jQuery plugin implementing it, so I decided to add one ...

Merge Sort

Continuing to evaluate efficient sorting algorithms, today we’ll look at merge sort. Merge sort[1] is a comparison sort using a divide and conquer algorithm, developed by John von Neumann[2] in 1945. It recursively divides the list into smaller sublists of length one, then repeatedly merges the sublists in order until there is only one sublist left. It has a worst case runtime of (O(nlogn)), making it worst-case more efficient than Quicksort.