Created
September 27, 2011 16:28
-
-
Save cowboy/1245543 to your computer and use it in GitHub Desktop.
shmemplates. req: needs to work x-domain and be fully cacheable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For Mike. | |
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)); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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>'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment