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


    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

  • 相关阅读:
    AVL树C++实现(end)
    B树/B+树
    树,森林,二叉树转换
    多路查找树
    变形版的九九乘法表
    原始版本的九九乘法表
    菱形变形-闪电
    菱形变形,对称+for循环
    菱形--for循环解决
    BZOJ 2037 区间DP
  • 原文地址:https://www.cnblogs.com/terrylin/p/3336391.html
Copyright © 2020-2023  润新知