Created
July 16, 2015 16:45
-
-
Save michaeljbailey/6a96fdae455efad84db9 to your computer and use it in GitHub Desktop.
Provides a general purpose sync-or-async template cache that builds on top of underscore's template engine. I make no guarantees this actually works, as I haven't tested this at all.
This file contains 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
(function() { | |
"use strict"; | |
if (!_) { | |
throw "Cannot find underscore.js"; | |
} | |
var TemplateCache = function(baseUrl) { | |
this.BaseUrl = baseUrl; | |
this.Templates = {}; | |
this.Load = function(templateName, async) { | |
if (templateName in this.Templates) { | |
var deferred = $.Deferred(); | |
deferred.resolve(); | |
return deferred.promise(); | |
} | |
return $.ajax({ | |
url: baseUrl + "/" + templateName + ".html", | |
dataType: "html", | |
method: "GET", | |
async: async, | |
success: function(data) { | |
this.LoadedTemplates[templateName] = _.template(data); | |
} | |
}); | |
}; | |
this.LoadAll = function(templateNames, async) { | |
var promises = []; | |
for (var i = 0; i < templateNames.length; i++) { | |
var templateName = templateNames[i]; | |
var promise = this.Load(templateName, async); | |
promises.push(promise); | |
} | |
return $.when(promises); | |
}; | |
this.RenderLoaded = function(templateName, data) { | |
var template = this.Templates[templateName]; | |
if (!template) { | |
throw "Template '" + templateName + "' has not been loaded"; | |
} | |
return template(data); | |
}; | |
this.Render = function(templateName, data, async) { | |
var templateData = { | |
model: data, | |
variable: "model" | |
}; | |
var render = this.RenderLoaded; | |
if (async) { | |
var deferred = $.Deferred(); | |
this.Load(templateName, true).then(function() { | |
var rendered = render(templateName, templateData); | |
deferred.resolve(rendered); | |
}, function() { | |
deferred.reject("Failed to load template '" + templateName + "'"); | |
}); | |
return deferred.promise(); | |
} else { | |
this.Load(templateName, false); | |
return render(templateName, templateData); | |
} | |
}; | |
}; | |
window.TemplateCache = TemplateCache; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment