Skip to content

Instantly share code, notes, and snippets.

@mpj
Created November 17, 2012 15:29
Show Gist options
  • Save mpj/4096805 to your computer and use it in GitHub Desktop.
Save mpj/4096805 to your computer and use it in GitHub Desktop.
Minimal String Template Source for Knockout
var templateEngine = createNativeStringTemplateEngine();
templateEngine.addTemplate('gigaScroll', "\
<div id=\"viewport\">\
<div id=\"gigaDiv\" data-bind=\"style: { height: gigaDivHeight() + 'px' }\">\
<ul data-bind=\"foreach: visibleItems, style: { paddingTop: offsetTop() + 'px' }\">\
<li data-bind="text: name" />
</ul>\
</div>\
</div>");
ko.renderTemplate("gigaScroll", viewModel, { templateEngine: templateEngine }, element, "replaceNode" );
// Less verbose implementation of
// http://www.knockmeout.net/2011/10/ko-13-preview-part-3-template-sources.html
var StringTemplate = function(text) {
var _data = {};
var _text = text;
this.data = function(key, value) {
if (!value) return _data[key];
_data[key] = value;
}
this.text = function(newValue) {
if (!newValue) return _text;
_text = newValue;
}
}
function createNativeStringTemplateEngine() {
var _templates = {};
var _nativeEngine = new ko.nativeTemplateEngine();
_nativeEngine.makeTemplateSource = function(templateName) {
return _templates[templateName];
}
_nativeEngine.addTemplate = function(name, body) {
_templates[name] = new StringTemplate(body);
}
return _nativeEngine;
}
@nathanboktae
Copy link

Cool! A couple of issues:

  1. Checking the falsy-ness of value and newValue is not the same as checking arguments.length - knockout won't be able to set null or empty string. probably not and issue for text but likely for data.
  2. you will have a better memory footprint per template to put data and text on StringTemplate.prototype rather than in the closure. (You are newing it up like a class for a reason, right?)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment