HTML and CSS Reference
In-Depth Information
function get(url, options) {
if (typeof url != "string") {
throw new TypeError("URL should be string");
var transport = ajax.create();"GET", url, true);
transport.onreadystatechange = function () {
if (transport.readyState == 4) {
requestComplete(transport, options);
ajax.get = get;
In order to avoid having the ajax.get method encompass everything but
the kitchen sink, handling the completed request was extracted into a separate
function. This forced the anonymous closure around the implementation, keeping
the helper function local. Finally, with an enclosing scope we could “import” the
tddjs.ajax namespace locally here, too. Wow, that was quite a bit of work. Tests
were run in between each operation, I promise. The important thing is that the tests
all run with this implementation.
You may wonder why we extracted requestComplete and not the whole
ready state handler. In order to allow the handler access to the options object,
we would have had to either bind the handler to it or call the function from inside
an anonymous function assigned to onreadystatechange . In either case we
would have ended up with two function calls rather than one in browsers without a
native bind implementation. For requests incurring a large response, the handler
will be called many times (with readyState 3), and the duplicated function calls
would have added unnecessary overhead.
Now then, what do you suppose would happen if the readystatechange
handler is called and we didn't provide a success callback? Listing 12.35 intends to
find out.
Search WWH ::

Custom Search