HTML and CSS Reference
In-Depth Information
Listing 11.35
Emptying the constructor
function Observable() {
}
Running the tests shows that all but one is now failing, all with the same message:
“this.observers is not defined.” We will deal with one method at a time. Listing 11.36
shows the updated
addObserver
method.
Listing 11.36
Defining the array if it does not exist in
addObserver
function addObserver(observer) {
if (!this.observers) {
this.observers = [];
}
/* ... */
}
Running the tests again reveals that the updated
addObserver
method fixes
all but the two tests that do not call it before calling other methods, such as
hasObserver
and
notifyObservers
. Next up, Listing 11.37 makes sure to
return
false
directly from
hasObserver
if the array does not exist.
Listing 11.37
Aborting
hasObserver
when there are no observers
function hasObserver(observer) {
if (!this.observers) {
return false;
}
/* ... */
}
We can apply the exact same fix to
notifyObservers
, as seen in Listing
11.38.
Listing 11.38
Aborting
notifyObservers
when there are no observers
function notifyObservers(observer) {
if (!this.observers) {
return;
}
/* ... */
}