Comment foreach binding vs foreach binding in knockoutjs

In my HTML, I can define these bindings for the foreach knockout:

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

against

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

Where are the differences between the two approaches?

+46
javascript templating knockout-templating
Jun 12 '13 at 14:27
source share
2 answers

Use inline binding when relationships between parents and children exist in the binding section, such as ul and li.

Use comment syntax to bind to the container if the bind section does not have a parent-child relationship.

In your example, you use the first block of code because you are not trying to associate it with a child structure. All you want to do is just bind your client data to the div, you do not need to create the parent div and foreach through the clients and add another div inside the parent div. This is more than you want.

Good use of oil free 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 your own binding , because that 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 looks silly. You add more complexity to something that doesn't have to be complicated.

+53
Jun 12 '13 at 15:19
source share
— -

In some cases, you may need to duplicate the markup section, but you do not have any container element on which you can bind the foreach binding

To handle this, you can use the control flow syntax without a container, which is based on comment tags

Details of the "foreach" binding mode , Note 4: Using foreach without a container element

+2
Jun 12 '13 at 14:32
source share



All Articles