knockout.jsknockout-3.0knockout-binding-handlers

Knockout binding iteration


I am having a scenario where based on the Observable flag I need to iterate ABC and XYZ

Current Code

<div  data-bind="visible: isEnabled">
           <ul data-bind="foreach: relatedObservalableArray">
               <li>
               <!-- Hundred lines of code>
               </li>
            </ul>
</div>


<div data-bind="visible: !isEnabled">
        <ul data-bind="foreach: unRelatedObservalableArray">
               <li>
                <!-- Same Hundred lines of code>
               </li>
            </ul>
   </div>

I am feeling code duplicate.

Is any way I can group the two html functions to a single one?

I want to change only in HTML part due to some other ...

I am new to Knockout. Can someone help me?


Solution

  • Sure you can use the knockout template binding for this. Read it more here.

    So for the changes it would be something like below but you can do variations basing on what you read from the link I gave.

    <script type="text/html" id="template-name">
       Hundred lines of code...
    </script>
    
    <div  data-bind="visible: isEnabled">
      <ul data-bind="foreach: relatedObservalableArray">
        <li data-bind="template: 'template-name'">
        </li>
      </ul>
    </div>
    
    
    <div data-bind="visible: !isEnabled">
      <ul data-bind="foreach: unRelatedObservalableArray">
         <li data-bind="template: 'template-name'">
         </li>
      </ul>
    </div>