External Native Templates for Knockout 1.3

  • Download Gist
ko.templateSources.externalHTML.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
(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);
}());

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.