Created
April 24, 2012 17:16
-
-
Save rpheath/2481622 to your computer and use it in GitHub Desktop.
Template Caching
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
// handles caching and rendering templates | |
var Template = (function() { | |
// initialize private method container | |
var TemplateHandler = function() {}; | |
// private methods | |
TemplateHandler.prototype = { | |
// used to hold the collection of | |
// key/value cached templates | |
templates: {}, | |
// caches a single template | |
cacheTemplate: function(name, cacheTemplateCallback) { | |
// capture the handler since $.get() will | |
// change the scope of 'this' | |
var templateHandler = this; | |
// cache the template and hand it to the callback | |
$.get(name, function(template) { | |
templateHandler.templates[name] = template; | |
cacheTemplateCallback.call(null, template); | |
}); | |
}, | |
// checks if a template has already been cached | |
templateIsCached: function(name) { | |
return this.templates[name]; | |
} | |
}; | |
// public methods | |
return({ | |
// PARAMETERS for Template.load() | |
// -> obj must contain *name* and *view* properties, | |
// where the *name* is the name/path to the template | |
// and *view* is the JSON data to be passed to the template | |
// -> callback will be passed the processed template HTML | |
// to later be injected into the DOM | |
load: function(obj, callback) { | |
var handler = new TemplateHandler(); | |
// if the template is cached, simply hand the Mustache'd | |
// version to the callback for injection into the DOM; | |
// otherwise, we need to cache it first | |
if (!handler.templateIsCached(obj.name)) { | |
handler.cacheTemplate(obj.name, function(template) { | |
callback.call(null, Mustache.to_html(template, obj.view)); | |
}); | |
} else { | |
callback.call(null, Mustache.to_html(handler.templates[obj.name], obj.view)); | |
} | |
} | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment