HTML and CSS Reference
In-Depth Information
Use a third-party library that provides either the missing method, or a similar
method
Which one of these approaches is best suited to solve a given problem will
depend on the situation; they all have their pros and cons. In the interest of keeping
Observable self-contained, we will simply implement hasObserver in terms
of a loop in place of the indexOf call, effectively working around the problem.
Incidentally, that also seems to be the “simplest thing that could possibly work” at
this point. Should we run into a similar situation later on, we would be advised to
reconsider our decision. Listing 11.20 shows the updated hasObserver method.
Listing 11.20 Manually looping the array
function hasObserver(observer) {
for (var i = 0, l = this.observers.length; i < l; i++) {
if (this.observers[i] == observer) {
return true;
}
}
return false;
}
11.3.2 Refactoring
With the bar back to green, it's time to review our progress. We now have three
tests, but two of them seem strangely similar. The first test we wrote to verify the
correctness of addObserver basically tests for the same things as the test we
wrote to verify hasObserver . There are two key differences between the two
tests: The first test has previously been declared smelly, as it directly accesses the
observers array inside the observable object. The first test adds two observers,
ensuring they're both added. Listing 11.21 joins the tests into one that verifies that
all observers added to the observable are actually added.
Listing 11.21 Removing duplicated tests
"test should store functions": function () {
var observable = new tddjs.util.Observable();
var observers = [function () {}, function () {}];
observable.addObserver(observers[0]);
observable.addObserver(observers[1]);
 
Search WWH ::




Custom Search