HTML and CSS Reference
In-Depth Information
11.6.2 Replacing the Constructor with an Object
Now that the constructor doesn't do anything, it can be safely removed. We will then
add all the methods directly to the
tddjs.util.observable
object, which can
then be used with, e.g.,
Object.create
or
tddjs.extend
to create observable
objects. Note that the name is no longer capitalized as it is no longer a constructor.
Listing 11.39 shows the updated implementation.
Listing 11.39
The
observable
object
(function () {
function addObserver(observer) {
/* ... */
}
function hasObserver(observer) {
/* ... */
}
function notifyObservers() {
/* ... */
}
tddjs.namespace("util").observable = {
addObserver: addObserver,
hasObserver: hasObserver,
notifyObservers: notifyObservers
};
}());
Surely, removing the constructor will cause all the tests so far to break. Fixing
them is easy, however; all we need to do is to replace the
new
statement with a call
to
Object.create
, as seen in Listing 11.40.
Listing 11.40
Using the
observable
object
in tests
TestCase("ObservableAddObserverTest", {
setUp: function () {
this.observable = Object.create(tddjs.util.observable);
},
/* ... */
});
TestCase("ObservableHasObserverTest", {
setUp: function () {