Skip to content

Instantly share code, notes, and snippets.

@dmaevac
Forked from mxriverlynn/1.js
Created April 10, 2012 15:40
Show Gist options
  • Save dmaevac/2352253 to your computer and use it in GitHub Desktop.
Save dmaevac/2352253 to your computer and use it in GitHub Desktop.
template cache
TemplateCache = {
get: function(selector){
if (!this.templates){ this.templates = {}; }
var template = this.templates[selector];
if (!template){
template = $(selector).html();
// precompile the template, for underscore.js templates
template = _.template(template);
this.templates[selector] = template;
}
return template;
},
compile: function(selector) {
}
}
TemplateCache = (function($, _) {
var templates = {},
getKey = function (selector) {
// strip out any chars that js might not like for object property names
return selector.replace(/[^a-zA-Z0-9]/,'');
},
compile = function(selector, key) {
// grab the template html
var template = $(selector).html(),
tpl;
// precompile the template, for underscore.js templates
tpl = _.template(template);
// assign & return
return templates[key] = tpl;
};
return {
get: function(selector){
var key = getKey(selector),
compiled = templates.hasOwnProperty(key) ? templates[key] : compile(selector, key);
return compiled;
}
};
})($, _);
TemplateCache = (function($, _) {
var templates = {},
templateCache = function(){};
templateCache.prototype = {
getKey: function (selector) {
// strip out any chars that js might not like for object property names
return selector.replace(/[^a-zA-Z0-9]/,'');
},
compile: function(selector, key) {
// grab the template html
var template = $(selector).html(),
tpl;
// precompile the template, for underscore.js templates
tpl = _.template(template);
// assign & return
return templates[key] = tpl;
},
get: function(selector){
var key = this.getKey(selector),
compiled = templates.hasOwnProperty(key) ? templates[key] : this.compile(selector, key);
return compiled;
}
};
return new templateCache();
})($, _);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment