Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
154
rated 0 times [  158] [ 4]  / answers: 1 / hits: 36878  / 11 Years ago, wed, june 12, 2013, 12:00:00

In my HTML I can define these knockout foreach bindings:



<!-- ko foreach: customer -->
<div data-bind=text: id />
<!-- /ko -->


vs



<div data-bind=foreach: customer>
<div data-bind=text: id />
</div>


Where are the differences between those two approaches?


More From » knockout.js

 Answers
6

Use native binding when a parent-child relationship exists within the binding section, like a ul and a li.



Use the comment syntax for containerless binding when your binding section does not have a parent-child relationship.



In your example you use the first code block because you are not trying to bind to a parent-child structure. All you want to do is just bind your customer data to a div, you shouldn't have to create a parent div and foreach through the customers and append another div inside of the parent div. It's more than you want to do.



Good use of containerless binding



<!-- ko foreach: customer -->
<section>
<p data-bind=text: customer.name></p>
<p data-bind=text: customer.orderDate></p>
</section>
<!-- /ko -->


However, if you have an ordered list you should use the native binding because it just makes sense.



Native



<ol data-bind=foreach: customer>
<li data-bind=text: customer.name></li>
</ol>


Containerless



<ol> 
<!-- ko foreach: customer -->
<li data-bind=text: customer.name></li>
<!-- /ko -->
</ol>


The second example just looks silly. You're adding more complexity for something that shouldn't be complicated.


[#77661] Tuesday, June 11, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
claudia

Total Points: 734
Total Questions: 106
Total Answers: 113

Location: Sweden
Member since Fri, Apr 16, 2021
3 Years ago
;