当前位置: 代码迷 >> 综合 >> knockout.js模板绑定之利用Underscore.js模板引擎示例
  详细解决方案

knockout.js模板绑定之利用Underscore.js模板引擎示例

热度:92   发布时间:2024-01-10 08:12:23.0

View代码

 1 <h1>People</h1>
 2 <ul data-bind="template: { name: 'peopleList' }"></ul>
 3 
 4 <script type="text/html" id="peopleList">
 5     <% _.each(people(), function(person) { %>
 6         <li>
 7             <b data-bind="text: person.name"></b> is <%= person.age %> years old
 8         </li>
 9     <% }) %>
10 </script>

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 elements
12             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());

 

在线示例:http://jsfiddle.net/6pStz/

官方说明:http://knockoutjs.com/documentation/template-binding.html