Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
xui js version 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;
var manager = this;
x$('body').xhr(this.getUrl(), {callback:function(){
manager.loaded=true;
manager.loading = false;
manager.currentTmpl(this.responseText);
},error: function(){
manager.loaded = true;
manager.loading = false;
manager.currentTmpl(ExternalTemplateSource.errorTemplate);
}});
}
}
}
// 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
Something went wrong with that request. Please try again.