HTML and CSS Reference
In-Depth Information
other two functions (and their tests) as an exercise. When you are done you will
note that one of the tests keep failing. We will deal with that last test together.
11.7.2 Supporting Events in notify
While updating notify to accept an event whose observers to notify, one of the
existing tests stays in the red. The test in question is the one that compares arguments
sent to notify against those received by the observer. The problem is that because
notify simply passes along the arguments it receives, the observer is now receiving
the event name in addition to the arguments it was supposed to receive.
To pass the test, Listing 11.44 uses Array.prototype.slice to pass along
all but the first argument.
Listing 11.44 Passing all but the first argument to observers
function notify(event) {
/* ... */
var args = Array.prototype.slice.call(arguments, 1);
for (var i = 0, l = this.observers.length; i < l; i++) {
try {
this.observers[i].apply(this, args);
} catch (e) {}
}
}
This passes the test and now observable has the interface to support events,
even if it doesn't actually support them yet.
The test in Listing 11.45 specifies how the events are supposed to work. It
registers two observers to two different events. It then calls notify for only one
of the events and expects only the related observer to be called.
Listing 11.45 Expecting only relevant observers to be called
"test should notify relevant observers only": function () {
var calls = [];
this.observable.observe("event", function () {
calls.push("event");
});
this.observable.observe("other", function () {
 
Search WWH ::




Custom Search