HTML and CSS Reference
In-Depth Information
Listing 11.25 Using apply to pass arguments through notifyObservers
function notifyObservers() {
for (var i = 0, l = this.observers.length; i < l; i++) {
this.observers[i].apply(this, arguments);
With this simple fix tests go back to green. Note that we sent in this as the
first argument to apply , meaning that observers will be called with the observable
as this .
11.5 Error Handling
At this point Observable is functional and we have tests that verify its behavior.
However, the tests only verify that the observables behave correctly in response to
expected input. What happens if someone tries to register an object as an observer
in place of a function? What happens if one of the observers blows up? Those are
questions we need our tests to answer. Ensuring correct behavior in expected situa-
tions is important—that is what our objects will be doing most of the time. At least
so we could hope. However, correct behavior even when the client is misbehaving
is just as important to guarantee a stable and predictable system.
11.5.1 Adding Bogus Observers
The current implementation blindly accepts any kind of argument to addOb-
server . This contrasts to the Java API we started out comparing to, which allows
objects implementing the Observer interface to register as observers. Although
our implementation can use any function as an observer, it cannot handle any value .
The test in Listing 11.26 expects the observable to throw an exception when at-
tempting to add an observer that is not callable.
Listing 11.26 Expecting non-callable arguments to cause an exception
"test should throw for uncallable observer": function () {
var observable = new tddjs.util.Observable();
assertException(function () {
}, "TypeError");
Search WWH ::

Custom Search