HTML and CSS Reference
In-Depth Information
Listing 12.35 Coping with successful requests and no callback
"test should not throw error without success handler":
function () {
this.xhr.readyState = 4;
this.xhr.status = 200;
assertNoException(function () {
Because we now need to access this.xhr inside the callback to assert-
NoException , we bind the callback. For this to work reliably across browsers,
save the Function.prototype.bind implementation from Chapter 6, Applied
Functions and Closures, in lib/function.js .
As expected, this test fails. ajax.get blindly assumes both an options object
and the success callback. To pass this test we need to make the code more defensive,
as in Listing 12.36.
Listing 12.36 Taking care with optional arguments
function requestComplete(transport, options) {
if (transport.status == 200) {
if (typeof options.success == "function") {
function get(url, options) {
/* ... */
options = options || {};
var transport = ajax.create();
/* ... */
With this safety net in place, the test passes. The success handler does not need
to verify the existence of the options argument. As an internal function we have
absolute control over how it is called, and the conditional assignment in ajax.get
guarantees it is not null or undefined .
Search WWH ::

Custom Search