码迷,mamicode.com
首页 > Web开发 > 详细

在knockout.js中使用underscore模板

时间:2014-11-11 10:43:16      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   ar   使用   java   sp   for   

view:

<h1>People</h1>
<ul data-bind="template: { name: ‘peopleList‘ }"></ul>

<script type="text/html" id="peopleList">
    <% _.each(people(), function(person) { %>
        <li>
            <b data-bind="text: person.name"></b> is <%= person.age %> years old
        </li>
    <% }) %>
</script>
        
<p>This shows that you can use both Underscore-style evaluation (<%= ... %>) <em>and</em> data-bind attributes in the same templates.</p>

 viewModel:

/* ---- Begin integration of Underscore template engine with Knockout. Could go in a separate file of course. ---- */
    ko.underscoreTemplateEngine = function () { }
    ko.underscoreTemplateEngine.prototype = ko.utils.extend(new ko.templateEngine(), {
        renderTemplateSource: function (templateSource, bindingContext, options) {
            // Precompile and cache the templates for efficiency
            var precompiled = templateSource[‘data‘](‘precompiled‘);
            if (!precompiled) {
                precompiled = _.template("<% with($data) { %> " + templateSource.text() + " <% } %>");
                templateSource[‘data‘](‘precompiled‘, precompiled);
            }
            // Run the template and parse its output into an array of DOM elements
            var renderedMarkup = precompiled(bindingContext).replace(/\s+/g, " ");
            return ko.utils.parseHtmlFragment(renderedMarkup);
        },
        createJavaScriptEvaluatorBlock: function(script) {
            return "<%= " + script + " %>";
        }
    });
    ko.setTemplateEngine(new ko.underscoreTemplateEngine());
/* ---- End integration of Underscore template engine with Knockout ---- */

var viewModel = {
    people: ko.observableArray([
        { name: ‘Rod‘, age: 123 },
        { name: ‘Jane‘, age: 125 },
    ])        
};
        
ko.applyBindings(viewModel);

 

在knockout.js中使用underscore模板

标签:style   blog   io   color   ar   使用   java   sp   for   

原文地址:http://www.cnblogs.com/lingtong/p/4088778.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!