Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If I understand correctly, jQuery will do what you want of it by way of Deferreds/promises.</p> <p>You can even generalise the remote template fetcher by </p> <ul> <li>using a js plain object in which to cache any number of templates</li> <li>renaming the function and passing a url to it, <code>get_remote_template(url)</code></li> </ul> <p>js :</p> <pre><code>var template_cache = {};//generalised template cache //generalised template fetcher function get_remote_template(url) { var dfrd = $.Deferred(); if(!template_cache[url]) { $.get(url).done(function(tpl) { template_cache[url] = tpl; //we use the url as a key. dfrd.resolve(tpl); }); } else { dfrd.resolve(template_cache[url]); } return dfrd.promise(); } </code></pre> <p>Then :</p> <pre><code>var url1 = "/my/remote/template"; //the url of a particular template get_remote_template(url1).done(function(tpl) { // Add initial things using tpl. }); </code></pre> <p>And, earlier or later :</p> <pre><code>$.get({ url: "/something/that/requires/an/asynchronous/callback", success: function(data) { init_remote_template(url1).done(function (tpl) { // Do something using tpl (and data). }); } }); </code></pre> <p>Note how <code>get_remote_template()</code> returns a promise. If the requested template is already cached, the promise is returned ready-resolved. If the template is not yet in cache (ie. it needs to be downloaded from the server), then the promise will be resolved some short time later. Either way, the fact that a promise is returned allows a <code>.done()</code> command to be chained, and for the appropriate template to be accessed and used.</p> <h2>EDIT</h2> <p>Taking @BenAlpert's points on board, this version caches the promise associated with a tpl rather than the tpl itself. </p> <pre><code>var template_cache = {};//generalised cache of promises associated with templates. //generalised template fetcher function get_remote_template(url) { if(!template_cache[url]) { template_cache[url] = $.get(url); } return template_cache[url];//this is a promise } </code></pre> <p>This version of <code>get_remote_template()</code> would be used in the same way as above.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload