AJAX - The Complete Reference

(avery) #1

440 Part II: Developing an Ajax Library^


A few examples will make these properties clear. Here we have a response that has a
URL and no template text.

{"average":3.37,"rating":"4","votes":475, "templateURL" :
"templates/ratingResult.tpl", "templateText" : "" }

In this case, the server tells the client where the template is located, but now it needs to
go and synchronously fetch it and apply the data. Fortunately though, a template cache
system is used, so once the template is returned, it will not have to be fetched again.

Utilizing a Template Cache
By default, the AjaxTCR library will cache templates, but you may indicate not to do this
by setting the option cacheTemplate to be false in a request. A call to AjaxTCR.comm
.setDefault("DEFAULT_CACHE_TEMPLATE", false) would set this globally. Some
template cache control facilities are also provided. For example, if you desire to clear the
template from the cache, you can use AjaxTCR.template.clearCache() which will clear
all entries or use AjaxTCR.template.removeFromCache() to specify the entry you are
interested in invalidating by its URL like so:

AjaxTCR.template.removeFromCache("templates/ratingResult.tpl");

NNOT EOTE You might wonder why the special “template cache” as opposed to just using the standard
cache mechanism as introduced in Chapter 6. The main issue here is that templates will generally
need to be quite sticky as they may be used longer than other requests. Separating the cache
systems was simply easier than introducing a complex mechanism to peg items into cache.

The template cache can be quite useful if you think about it carefully. For example, if
you desire to load up templates upon page load you can utilize the AjaxTCR.template
.cache() method and pass it the URLs of the templates you plan on using.

AjaxTCR.util.event.addWindowLoadEvent(function () {
AjaxTCR.template.cache("templates/header.tpl");
AjaxTCR.template.cache("templates/footer.tpl");
AjaxTCR.template.cache("templates/popup.tpl");
});

NNOT EOTE When attempting to cache templates upon page load, it is possible, given latency and
simultaneous requests, that all templates may not be loaded before usage. This will not error if
the template is used as part of a standard request because the request will still be made for the
template, though likely the queued request will service that need first.

Now if you have a complex application, you may want to load quite a number of
separate templates right away. However, if you do this you will see numerous requests
going out which may not be very efficient. To address this, we adopt a simple bundling
mechanism that can be invoked: AjaxTCR.template.cacheBundle(URL), where the URL
is a bundled template file in which a simple delimiter system is utilized that allows
numerous templates to be included in a single file with their own URL indicators. An
example bundled template would look like this:
Free download pdf