Using the underscore template in Knockout.js

Source: Internet
Author: User

View

<H1>People</H1><ulData-bind= "Template: {name: ' peoplelist '}"></ul><Scripttype= "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 the 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 (NewKo.templateengine (), {rendertemplatesource:function(Templatesource, BindingContext, options) {//precompile and cache the templates for efficiency            varprecompiled = templatesource[' data ' (' precompiled ')); if(!precompiled) {Precompiled= _.template ("<% with ($data) {%>" + templatesource.text () + "<%}%>"); templatesource[' Data ' (' precompiled '), precompiled); }            //Run the template and parse its output to an array of DOM elements            varRenderedmarkup = Precompiled (BindingContext). Replace (/\s+/g, ""); returnko.utils.parseHtmlFragment (renderedmarkup); }, Createjavascriptevaluatorblock:function(script) {return"<%=" + script + "%>";    }    }); Ko.settemplateengine (Newko.underscoretemplateengine ());/*----END integration of underscore template engine with Knockout----*/varViewModel ={People:ko.observableArray ([{name:' Rod ', age:123}, {name:' Jane ', age:125 },    ])        }; Ko.applybindings (ViewModel);

Using the underscore template in Knockout.js

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.