HTML and CSS Reference
In-Depth Information
observable.notifyObservers() , which has a single optional argument
(which in turn can be any object, often the observable itself). The notifyOb-
servers method in turn calls the update method on each observer, allowing
them to act in response.
11.1 The Observer in JavaScript
JavaScript traditionally lives in the browser, where it is used to power dynamic user
interfaces. In the browser, user actions are handled asynchronously by way of DOM
event handlers. In fact, the DOM event system we already know is a great example
of the Observer pattern in practice. We register some function (the observer) as
an event handler with a given DOM element (the observable). Whenever some-
thing interesting happens to the DOM element, i.e., someone clicks or drags it, the
event handler is called, allowing us to make magic happen in response to the user's
Events appear many other places in JavaScript programming as well. Consider
an object that adds live search to an input field. Live search is the kind that uses
the XMLHttpRequest object to continuously perform server-side searches as the
user types, narrowing down the list of hits as the search phrase is typed out. The
object would need to subscribe handlers to DOM events fired by keyboard typing
in order to know when to search. It would also assign a handler to the onreadys-
tatechange event of the XMLHttpRequest object to know when results are
When the server comes back with some search results, the live search object
may choose to update its result view by way of an animation. To allow further
customization, the object may offer clients a few custom callbacks. These callbacks
can be hard-coded to the object or, preferably, it can make use of a generic solution
for handling observers.
11.1.1 The Observable Library
As discussed in Chapter 2, The Test-Driven Development Process, the test-driven
development process allows us to move in very small steps when needed. In this first
real-world example we will start out with the tiniest of steps. As we gain confidence
in our code and the process, we will gradually increase the size of our steps when
circumstances allow it (i.e., the code to implement is trivial enough). Writing code
in small frequent iterations will help us design our API piece-by-piece, as well as
help us make fewer mistakes. When mistakes occur, we will be able to fix them
Search WWH ::

Custom Search