HTML and CSS Reference
In-Depth Information
calls.push("other");
});
this.observable.notify("other");
assertEquals(["other"], calls);
}
The test obviously fails as the observable happily notifies all the observers. There
is no trivial way to fix this, so we roll up our sleeves and replace the observable
array with an object.
The new object should store observers in arrays on properties whose keys are
event names. Rather than conditionally initializing the object and array in all the
methods, we can add an internal helper function that retrieves the correct array
for an event, creating both it and the object if necessary. Listing 11.46 shows the
updated implementation.
Listing 11.46 Storing observers in an object rather than an array
(function () {
function _observers(observable, event) {
if (!observable.observers) {
observable.observers = {};
}
if (!observable.observers[event]) {
observable.observers[event] = [];
}
return observable.observers[event];
}
function observe(event, observer) {
if (typeof observer != "function") {
throw new TypeError("observer is not function");
}
_observers(this, event).push(observer);
}
function hasObserver(event, observer) {
var observers = _observers(this, event);
for(vari=0,l=observers.length; i < l; i++) {
 
Search WWH ::




Custom Search