O'Reilly logo

Maintainable JavaScript by Nicholas C. Zakas

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 in to 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"); popup.style.left ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required