官术网_书友最值得收藏!

  • Mastering KnockoutJS
  • Timothy Moran
  • 196字
  • 2021-08-05 17:13:12

Containerless control flow

So far, we have looked at using the control flow bindings (if, with, foreach, and template) and the standard data-bind attribute on an HTML element. It is also possible to use control flow bindings without an element by using special comment tags that are parsed by Knockout. This is called containerless control flow.

Adding a <!— ko --> comment starts a virtual element that ends with a <!-- /ko --> comment. This virtual element causes a control flow binding to treat all contained elements as children. The following block of code demonstrates how sibling elements can be grouped by a virtual comment container:

<ul>
    <li>People</li>
    <li>Locations</li>
    <!-- ko if: isAdmin -->
    <li>Users</li>
    <li>Admin</li>
    <!-- /ko -->
</ul>

List elements only allow specific elements as children. The preceding containerless syntax applies the if binding to the last two elements in the list, which causes them to add or remove from the DOM based in the isAdmin property:

<ul>
    <li>Nav Header</li>
    <!-- ko foreach: navigationItems -->
    <li><span data-bind="text: $data"></span></li>
    <!-- /ko -->
</ul>

The preceding containerless syntax allows us to have a foreach binding to create a list of items while maintaining a header item at the top of the list.

All of the control flow bindings can be used in this way. The preceding two examples can be seen in the cp1-containerless branch.

主站蜘蛛池模板: 泾川县| 浪卡子县| 永康市| 拉孜县| 安化县| 朝阳市| 定襄县| 天峨县| 凤山市| 佳木斯市| 广西| 沙洋县| 宽甸| 丰镇市| 利川市| 那坡县| 鄂托克旗| 桂阳县| 宜良县| 元朗区| 怀仁县| 逊克县| 胶州市| 梧州市| 扎赉特旗| 贵溪市| 泰顺县| 卢氏县| 兴山县| 芜湖县| 涞源县| 措勤县| 大荔县| 青川县| 阳新县| 东辽县| 通化县| 曲阳县| 巴东县| 平远县| 盘锦市|