HTML and CSS Reference
In-Depth Information
Listing 11.23 Calling observers
function notifyObservers() {
for (var i = 0, l = this.observers.length; i < l; i++) {
Observable.prototype.notifyObservers = notifyObservers;
11.4.2 Passing Arguments
Currently the observers are being called, but they are not being fed any data. They
know something happened, but not necessarily what. Although Java's implemen-
tation defines the update method of observers to receive one or no arguments,
JavaScript allows a more flexible solution. We will make notifyObservers take
any number of arguments, simply passing them along to each observer. Listing 11.24
shows the requirement as a test.
Listing 11.24 Expecting arguments to notifyObservers to be passed
to observers
"test should pass through arguments": function () {
var observable = new tddjs.util.Observable();
var actual;
observable.addObserver(function () {
actual = arguments;
observable.notifyObservers("String", 1, 32);
assertEquals(["String", 1, 32], actual);
The test compares passed and received arguments by assigning the received
arguments to a variable that is local to the test. Running the test confirms that it
fails, which is not surprising as we are currently not touching the arguments inside
notifyObservers .
To pass the test we can use apply when calling the observer, as seen in
Listing 11.25.
Search WWH ::

Custom Search