Skip to content Skip to sidebar Skip to footer

How To Properly Code Foreach And Style Binding

I have prepared a small jsfiddle here: http://jsfiddle.net/zb8jwre6/ Basically, I have observable array of sliders, and each slider should have it's own observable array of segment

Solution 1:

I've changed

self.segments = ko.observableArray([segments]);

with

self.segments = ko.observableArray(segments);

See: http://jsfiddle.net/x4a8pkmu/

I would like to know what foreach binding should I use. When can I use "comment" foreach bindng and when do I use normal one, and I would like to know how to rework my code, so I can bind CSS properties from segments observable array

The "comment" syntax is useful if you do not want a container element. For example:

<ul><!-- ko foreach: myList --><lidata-bind="text: myProp"></li><!-- /ko --></ul>

produces the same effects as:

<uldata-bind="foreach: myList"><lidata-bind="text: myProp"></li></ul>

Solution 2:

  • The point of making a variable an observable is if you are going to change these values based on user interaction/server response, and then updating the UI. If the values are never going to change then using an observable for the style properties isn't helpful.
  • There is a very small difference between the two foreach loops - 'Comment' foreach does not have a parent div tag around the repeating child tags, while the other one does. So the outputs would look like:

Comment foreach:

<p>MON</p>
<p>TUE</p>
<p>WED</p>

Div foreach:

<div>
    <p>MON</p>
    <p>TUE</p>
    <p>WED</p>
</div>

The comment foreach is useful for cases like these:

<ul><liclass="header">Header item</li><!-- ko foreach: myItems --><li>Item <spandata-bind="text: $data"></span></li><!-- /ko --></ul>

Post a Comment for "How To Properly Code Foreach And Style Binding"