View代码
1People
2
ViewModel
1 var viewModel = {2 people: ko.observableArray([3 { name: 'Rod', age: 123 },4 { name: 'Jane', age: 125 },5 ]) 6 };7 8 ko.applyBindings(viewModel);
整合underscore模板引擎与knockout.js
1 // 可以单独放在一个js文件中 2 ko.underscoreTemplateEngine = function () { } 3 ko.underscoreTemplateEngine.prototype = ko.utils.extend(new ko.templateEngine(), { 4 renderTemplateSource: function (templateSource, bindingContext, options) { 5 // 预编译和缓存效率的模板 6 var precompiled = templateSource['data']('precompiled'); 7 if (!precompiled) { 8 precompiled = _.template("<% with($data) { %> " + templateSource.text() + " <% } %>"); 9 templateSource['data']('precompiled', precompiled);10 }11 // 运行模板并解析成 DOM elements12 var renderedMarkup = precompiled(bindingContext).replace(/\s+/g, " ");13 return ko.utils.parseHtmlFragment(renderedMarkup);14 },15 createJavaScriptEvaluatorBlock: function(script) {16 return "<%= " + script + " %>";17 }18 });19 ko.setTemplateEngine(new ko.underscoreTemplateEngine());
在线示例:
官方说明: