Chapter 13. Surviving events

 

This chapter covers

  • Why events are such an issue
  • Techniques for binding and unbinding events
  • Triggering events
  • Using custom events
  • Event bubbling and delegation

The management of DOM events should be relatively simple, but, as you may have guessed by the fact that we’re devoting an entire chapter to it, sadly it’s not.

Although all browsers provide relatively stable APIs for managing events, they do so with differing approaches and implementations. And even beyond the challenges posed by browser differences, the features that are provided by the browsers are insufficient for most of the tasks that need to be handled by even somewhat complex applications.

Because of these shortcomings, JavaScript libraries end up needing to nearly duplicate the existing browser event-handling APIs. This book doesn’t assume that you’re writing your own library (it doesn’t not assume that either), but it’s useful to understand how things like event handling are being handled by any library you might choose to use, and it’s helpful to know what secrets went into creating their implementations in the first place.

Everyone who’s made it this far into the book is likely to be familiar with the typical use of the DOM Level 0 Event Model, in which the event handlers are established via element properties or attributes. For example, if the code is ignoring the principles of unobtrusive JavaScript, establishing an event handler for the body element might look like this:

13.1. Binding and unbinding event handlers

13.2. The Event object

13.3. Handler management

13.4. Triggering events

13.5. Bubbling and delegation

13.6. The document ready event

13.7. Summary