AJAX - The Complete Reference

(avery) #1

274 Part II: Developing an Ajax Library^


the code first looks at the flag to see if response caching is enabled. If so, it determines if
the user set a cacheKey. By default, the URL is used as the key in the cache, but in the
case of POST requests, the URL will be the same, so the developer may decide to set the
key for a request themselves. Now the cache is searched by calling the public function
AjaxTCR.comm.cache.get(request.cacheKey) and passing it the key for the request
in question. If data is found, _handleCacheResponse() is called and if not the request
is sent normally. The outline of this part of sendRequest() is shown here:

var cachedResponse = null;
/* Check if the item is in the cache first */
if (request.cacheResponse)
{
/* Check to see if we have a key for our cache */
if (request.cacheKey == undefined)
request.cacheKey = request.url;

cachedResponse = AjaxTCR.comm.cache.get(request.cacheKey);
if (cachedResponse)
AjaxTCR.comm.cache._handleCacheResponse(request, cachedResponse);
}
/* invoke the request */
if (!cachedResponse)
AjaxTCR.comm._makeRequest(request);

Now the get() function looks through the cache to find the object. If it is found, it
checks first to make sure it hasn’t expired. If so, it removes it; otherwise, it updates the
access properties for the object (lastAccessed and totalAccessed) and returns the value.
If the object is not found, the method returns null.
As shown in the previous example, if the request is found in cache, the actual XHR is
never issued, instead _handleCacheResponse()is called. This method, in some sense,
fakes the result so the various callbacks can be invoked, but if there is any concern about
this not being a network response, it sets a flag fromCache in the response object for good
measure.

_handleCacheResponse : function(response, responseText){
response.xhr = {};
response.xhr.responseText = responseText;
response.xhr.status = 200;
response.xhr.responseXML = null;
response.fromCache = true;
AjaxTCR.comm._handleResponse(response);
}

In order to get an item into cache, the responses returned need to be saved. A public
method, add(key,value), adds the item to the cache and adjusts the cache contents based
upon the particular algorithm in play, potentially removing an item. This function is called
in _handleResponse() based upon the flag being set, the item not being in cache already
(now you see why that flag was previously set), and being a successful result.

/* Cache Response */
if (!response.fromCache && response.cacheResponse && response.xhr.status == 200)
AjaxTCR.comm.cache.add (response.cacheKey, response.xhr.responseText);
Free download pdf