HTML and CSS Reference
In-Depth Information
Listing 13.58
Only connect once
function connect() {
if (!this.poller) {
this.poller = ajax.poll(this.url);
}
}
Listing 13.59 tests for a missing
url
property.
Listing 13.59
Expecting missing URL to cause an exception
"test connect should throw error if no url exists":
function () {
var client = Object.create(ajax.cometClient);
ajax.poll = stubFn({});
assertException(function () {
client.connect();
}, "TypeError");
}
Passing this test is three lines of code away, as seen in Listing 13.60.
Listing 13.60
Throwing an exception if there is no URL
function connect() {
if (!this.url) {
throw new TypeError("client url is null");
}
if (!this.poller) {
this.poller = ajax.poll(this.url);
}
}
The final missing piece is the success handler that should call
dispatch
with
the returned data. The resulting data will be a string of JSON data, which needs
to be passed to
dispatch
as an object. To test this we will use the
fakeXML-
HttpRequest
object once again, to simulate a completed request that returns with
some JSON data. Listing 13.61 updates the
fakeXMLHttpRequest.complete
method to accept an optional response text argument.