Skip to content

Instantly share code, notes, and snippets.

@andrewharry
Created November 22, 2011 23:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save andrewharry/a432c98834a72e018aa6 to your computer and use it in GitHub Desktop.
Save andrewharry/a432c98834a72e018aa6 to your computer and use it in GitHub Desktop.
External Native Templates for Knockout 1.3
(function(){
// Loads an external native template if one is not found in the dom
var ExternalTemplateSource = function(templateName) {
this.templateName = templateName;
this.loaded = false;
this.loading = false;
this.currentTmpl = ko.observable(ExternalTemplateSource.loadingTemplate);
this.currentTmpl.data = {};
}
// Static loading/error templates for easy, albeit global customization
// might look into using the options object to specify these
// and configure things like async...
ExternalTemplateSource.loadingTemplate = "Loading...";
ExternalTemplateSource.errorTemplate = "Error!";
// Prefix and postfix for urls
ExternalTemplateSource.urlPrefix = "";
ExternalTemplateSource.urlPostfix = ".html";
// Class Definition
ExternalTemplateSource.prototype = {
//read/write meta-data about the template (has it been rewritten already; not used for native templates currently)
data: function(key, value) {
if (arguments.length === 1) {
return this.currentTmpl.data[key];
}
this.currentTmpl.data[key] = value;
},
//read/write the actual template text
text: function(value) {
if (!this.loaded) {
this.getTemplate();
}
if (arguments.length === 0) {
return this.currentTmpl();
} else {
this.currentTmpl(arguments[0]);
}
},
getUrl: function() {
return ExternalTemplateSource.urlPrefix + this.templateName + ExternalTemplateSource.urlPostfix;
},
//retrieve our actual template via AJAX
getTemplate: function() {
if (!this.loading && !this.loaded) {
this.loading = true;
$.ajax({
url: this.getUrl(),
context: this,
success: function(data) {
this.loaded = true;
this.loading = false;
this.currentTmpl(data);
},
error: function(data) {
this.loaded = true;
this.loading = false;
this.currentTmpl(ExternalTemplateSource.errorTemplate);
},
dataType: 'html'
});
}
}
}
// Create an instance of
var ExternalTemplateEngine = new ko.nativeTemplateEngine();
ExternalTemplateEngine.cachedSources = {};
ExternalTemplateEngine.makeTemplateSource = function(templateName) {
if (typeof templateName == "string") {
if (this.cachedSources[templateName] == undefined) {
this.cachedSources[templateName] = new ExternalTemplateSource(templateName);
}
return this.cachedSources[templateName];
}
return new ko.templateSources.anonymousTemplate(templateName); // Anonymous template
}
// Expose the source and engine publically
ko.templateSources.externalHTML = ExternalTemplateSource;
ko.setTemplateEngine(ExternalTemplateEngine);
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment