ThomasBurleson
11/17/2011 - 1:54 AM

Promises: template caching w/ $.getScript()

Promises: template caching w/ $.getScript()

// You do this in your code:
var tmpl = Bocoup.utils.template('header');
$.when(tmpl, otherAjaxRequest).then(function(tmpl, ajaxResponse) {
  // something with tmpl and ajaxResponse
});

tmpl.done(function(tmpl) {
  // something with tmpl
});

// FWIW, the server sends back this:
Bocoup.utils.template.handle('header', '<h1>{{header}}</h1>');
// shmemplates. req: needs to work x-domain and be fully cacheable

Bocoup.utils.template = (function($) {
  // Request a template from the server. Returns a Deferred object.
  function fn(key) {
    return $.Deferred(function(dfd) {
      if (key in fn.cache) {
        dfd.resolve(fn.cache[key]);
      } else {
        $.getScript(fn.url + key, function() {
          dfd.resolve(fn.cache[key]);
        });
      }
    });
  }
  // The cache.
  fn.cache = {};
  // The URL.
  fn.url = 'http://server.com/templates/';
  // The server-generated JavaScript calls this function.
  fn.handle = function(key, tmpl) {
    fn.cache[key] = Handlebars.compile(tmpl);
  };
  // Expose the interface.
  return fn;
}(jQuery));