首页 > 代码库 > 在knockout.js中使用underscore模板
在knockout.js中使用underscore模板
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模板
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。