Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockout template binding

I have an ul element which is filled through template binding.

<script type="text/html" id="someTemplate">
<li>
   <span data-bind="text: someText">
</li>
</script>

<ul data-bind="template: {foreach: someElemets, name: 'someTemplate'}">
</ul>

But I want the first li-tag would not be li-tag from template but another one with button in it and it will not be connected to someElemets array. If I do in that way

<ul data-bind="template: {foreach: someElemets, name: 'someTemplate'}">
    <li><button data-bind=click: doSomething">Click me</button></li>
</ul>

then li-tag with button will be the last one after rendering. What is the best way to solve that problem?

like image 810
avgorohov Avatar asked Feb 14 '12 12:02

avgorohov


People also ask

What is binding in knockout?

Essentially a binding or a data binding is a way to link your ViewModels to your Views(templates) and vice versa. KnockoutJS uses two-way data binding, which means changes to your ViewModel influence the View and changes to your View can influence the ViewModel.

What is Ko template?

Advertisements. Template is a set of DOM elements which can be used repetitively. Templating makes it easy to build complex applications due to its property of minimizing duplication of DOM elements.

For what purpose do we use foreach binding in Ko?

Purpose. The foreach binding duplicates a section of markup for each entry in an array, and binds each copy of that markup to the corresponding array item. This is especially useful for rendering lists or tables.


2 Answers

You can use containerless control flow syntax, databinding using comment tags. No need for a template. more info

<ul>     
    <li><button data-bind=click: doSomething">Click me</button></li>
    <!-- ko foreach: someElemets-->         
    <li>
        <span data-bind="text: someText"></span>
    </li>    
    <!-- /ko -->
</ul> 
like image 145
Bart W Avatar answered Oct 28 '22 05:10

Bart W


The following will do it:

<!-- ko template: { name: 'template-name', data: vm } --> <!-- /ko -->
like image 30
Maksym Kozlenko Avatar answered Oct 28 '22 05:10

Maksym Kozlenko