Chapter 7. Event Handling

Event handling is an important part of any JavaScript application. All JavaScript is tied to the UI through events, so most web developers spend much of their time coding and modifying event handlers. Unfortunately, this is also an area of JavaScript programming that hasn’t received much attention since the language was first introduced. Even as developers started to embrace more traditional concepts of architecture in JavaScript, event handling was one of those areas in which little has changed. Most event-handling code is very tightly coupled to the event environment (what is available to the developer at the time an event is fired) and therefore is not very maintainable.

Classic Usage

Most developers are familiar with the event object that is passed into an event handler when the event is fired. The event object contains all of the information related to the event, including the event target as well as additional data based on the event type. Mouse events expose additional location information on the event object, keyboard events expose information about keys that have been pressed, and touch events expose information about the location and duration of touches. All of this information is provided so that the UI can react appropriately.

In many cases, however, you end up using a very small subset of the information present on event. Consider the following:

// Bad function handleClick(event) { var popup = document.getElementById("popup"); ...

Get Maintainable JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.