How to properly code foreach and style binding

2020-05-07 02:11发布

问题:

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 segments, which contain some properties for CSS-binding in HTML.

My first problem is that I'am not sure which foreach bind should i use:

This one doesn't work for some reason:

<div data-bind "foreach: $root.sliders">
   <p data-bind="text: day"></p>
</div>

This one works, but I am not sure in which cases should I use this one:

<!-- ko foreach: sliders-->
   <p data-bind="text: day"></p>
<!-- /ko -->

My second problem is that I don't know how to apply wanted CSS stylings from segment observable array.

I have tried this:

<div class='slider-segment' data-bind= "style: {left: segment_left, width: 
segment_width, backgroundColor: segment_color}"></div>

But this does not work. I think I need to make those properties also as observables, but I am not sure how to do this properly in ViewModel

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.

Thank you!

回答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 -->
    <li data-bind="text: myProp"></li>
<!-- /ko -->
</ul>

produces the same effects as:

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


回答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>
    <li class="header">Header item</li>
    <!-- ko foreach: myItems -->
        <li>Item <span data-bind="text: $data"></span></li>
    <!-- /ko -->
</ul>