Created
November 17, 2012 15:29
-
-
Save mpj/4096805 to your computer and use it in GitHub Desktop.
Minimal String Template Source for Knockout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" ); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Cool! A couple of issues:
value
andnewValue
is not the same as checkingarguments.length
- knockout won't be able to set null or empty string. probably not and issue fortext
but likely fordata
.data
andtext
onStringTemplate.prototype
rather than in the closure. (You are newing it up like a class for a reason, right?)