Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint

CUSTOM EVENTS

Earlier in this book, you learned that events are the primary way in which JavaScript interacts with the browser. Events are a type of design pattern called an observer, which is a technique for creating loosely coupled code. The idea is that objects can publish events indicating when an interesting moment in the object’s life cycle occurs. Other objects can then observe that object, waiting for these interesting moments to occur and responding by running code.

The observer pattern is made up of two types of objects: a subject and an observer. The subject is responsible for publishing events, and the observer simply observes the subject by subscribing to these events. A key concept for this pattern is that the subject doesn’t know anything about the observer, meaning that it can exist and function appropriately even if the observer isn’t present. The observer, on the other hand, knows about the subject and registers callbacks (event handlers) for the subject’s events. When you’re dealing with the DOM, a DOM element is the subject and your event-handling code is the observer.


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial