HTML and CSS Reference
In-Depth Information
As expected, the test now fails. The test expects that functions added as ob-
servers should stack up like any element added to an array. To achieve this, we
will move the array instantiation into the constructor and simply delegate addOb-
server to the array method push as Listing 11.14 shows.
Listing 11.14 Adding arrays the proper way
function Observable() {
this.observers = [];
}
function addObserver(observer) {
this.observers.push(observer);
}
With this implementation in place, the test passes again, proving that we have
taken care of the hard-coded solution. However, accessing a public property and
making wild assumptions about the implementation of Observable is still an
issue. An observable object should be observable by any number of objects, but it
is of no interest to outsiders how or where the observable stores them. Ideally, we
would like to be able to check with the observable if a certain observer is registered
without groping around its insides. We make a note of the smell and move on. Later,
we will come back to improve this test.
11.3 Checking for Observers
We will add another method to Observable , hasObserver , and use it to remove
some of the clutter we added when implementing addObserver .
11.3.1 The Test
A new method starts with a new test. Listing 11.15 describes the desired behavior
for the hasObserver method.
Listing 11.15 Expecting hasObserver to return true for existing observers
TestCase("ObservableHasObserverTest", {
"test should return true when has observer": function () {
var observable = new tddjs.util.Observable();
var observer = function () {};
observable.addObserver(observer);
 
 
Search WWH ::




Custom Search