Skip to content

Instantly share code, notes, and snippets.

@andrew-aladev
Created June 19, 2014 16:58
Show Gist options
  • Save andrew-aladev/28ae72f892e4df6796a9 to your computer and use it in GitHub Desktop.
Save andrew-aladev/28ae72f892e4df6796a9 to your computer and use it in GitHub Desktop.
Knockout asynchronous templates
(function(undefined) {
"use strict";
if (!ko.templates) {
ko.templates = {};
}
if (!ko.templates_data) {
ko.templates_data = {};
}
var StringTemplate = function(template) {
this.template = template;
}
StringTemplate.prototype.data = function (key, value) {
ko.templates_data[this.template] = ko.templates_data[this.template] || {};
if (arguments.length == 1) {
return ko.templates_data[this.template][key];
}
ko.templates_data[this.template][key] = value;
}
StringTemplate.prototype.text = function (value) {
if (arguments.length == 0) {
var template = ko.templates[this.template];
if (template == null) {
throw Error("Template not found : " + this.template);
}
return template;
}
ko.templates[this.template] = value;
}
ko.templateSources.stringTemplate = StringTemplate;
var Engine = ko.nativeTemplateEngine.clone();
Engine.prototype.makeTemplateSource = function (template, options, template_document, callback) {
if (typeof template == "string") {
if (typeof options == "object" && options.url) {
if (ko.templates[template]) {
callback(new StringTemplate(template));
} else {
$.get(options.url, function (template_data) {
$(template_data).find("script").addBack("script").each(function() {
ko.templates[$(this).attr("id")] = $(this).html();
});
callback(new StringTemplate(template));
});
}
} else {
var element = template_document.getElementById(template);
if (element) {
callback(new ko.templateSources.domElement(template));
} else {
callback(new StringTemplate(template));
}
}
} else if (typeof template == "object") {
if (template.nodeType == 1 || template.nodeType == 8) {
callback(new ko.templateSources.anonymousTemplate(template));
} else {
throw new Error("Unknown template type : " + template);
}
} else {
throw new Error("Unknown template type : " + template);
}
}
Engine.prototype.renderTemplate = function (template, binding_context, options, template_document, callback) {
var self = this;
this.makeTemplateSource(template, options, template_document, function (template_source) {
self.renderTemplateSource(template_source, binding_context, options, callback);
});
}
ko.setTemplateEngine(new Engine());
}) ();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment