HTML and CSS Reference
In-Depth Information
assertTrue(observable.hasObserver(observers[0]));
assertTrue(observable.hasObserver(observers[1]));
}
11.4 Notifying Observers
Adding observers and checking for their existence is nice, but without the ability
to notify them of interesting changes, Observable isn't very useful.
In this section we will add yet another method to our library. Sticking to the Java
parallel, we will call the new method notifyObservers . Because this method
is slightly more complex than the previous methods, we will implement it step by
step, testing a single aspect of the method at a time.
11.4.1 Ensuring That Observers Are Called
The most important task notifyObservers performs is calling all the observers.
To do this, we need some way to verify that an observer has been called after the
fact. To verify that a function has been called, we can set a property on the function
when it is called. To verify the test we can check if the property is set. The test in
Listing 11.22 uses this concept in the first test for notifyObservers .
Listing 11.22 Expecting notifyObservers to call all observers
TestCase("ObservableNotifyObserversTest", {
"test should call all observers": function () {
var observable = new tddjs.util.Observable();
var observer1 = function () { observer1.called = true; };
var observer2 = function () { observer2.called = true; };
observable.addObserver(observer1);
observable.addObserver(observer2);
observable.notifyObservers();
assertTrue(observer1.called);
assertTrue(observer2.called);
}
});
To pass the test we need to loop the observers array and call each function.
Listing 11.23 fills in the blanks.
 
 
Search WWH ::




Custom Search