Durandal Widget: Knockout "<!-- ko if: -->" anomaly

dom, durandal, knockout.js, widget

Solution

Durandal requires to have one logical root element of your views/windgets. It also removes root level comments.

So you need to wrap your widget html into an additional `div` to make it work:

<div>
  <div data-bind="visible: menuItems().length > 0">
       greater
  </div>

  <div data-bind="visible: menuItems().length == 0">
       equal
  </div>

  <!-- ko if: menuItems().length == 0 -->
  <form role="form">
       <fieldset>
          <legend>Members</legend>
           //teh form markup
       </fieldset>
  </form>
  <!-- /ko -->
  <!-- ko if: menuItems().length > 0 -->
   <h2 data-bind="text: settings.header"></h2>
   <ul data-bind="foreach: menuItems()">
      <li>
       <a href='#' data-bind='click: $data.itemClick, text: $data.name'></a>
      </li>
   </ul>
  <!-- /ko -->
</div>

Problem

I've come across something strange. (To me at least) And not sure what the best route would be to correct this as id like to make use of a widget in this case, and not have my markup actually render when there isn't data ``` <div data-bind="visible: menuItems().length > 0"> greater </div> <div data-bind="visible: menuItems().length == 0"> equal </div> <!-- ko if: menuItems().length == 0 --> <form role="form"> <fieldset> <legend>Members</legend> //teh form markup </fieldset> </form> <!-- /ko --> <!-- ko if: menuItems().length > 0 --> <h2 data-bind="text: settings.header"></h2> <ul data-bind="foreach: menuItems()"> <li> <a href='#' data-bind='click: $data.itemClick, text: $data.name'></a> </li> </ul> <!-- /ko --> ``` FIG A In this case my menu items count was 0. But both the if statement containing code parts still render. EG header and ul (FIG A) If I inspect the code via chrome. I can see that the "`<!-- ko if: menuItems().length == 0 -->`" is missing.... (FIG B) Which explains why the containing content is still there... my assumption is that "`<!-- you get the idea -->`" gets excluded somehow. Could this be to do with how markup gets rendered etc? Does it get commented code sections get excluded during the widget binding/DOM creation process? Thus my header and ul renders, (the collection is empty, which equals an empty ul)... both of which should not be there in this case... FIG B When i set the menu items to > 3, the only difference is that the word "greater" gets displayed & i have menu items... and still a form :/ No comprehendo

Original source