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

  • 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.

主站蜘蛛池模板: 连城县| 昌吉市| 苏州市| 改则县| 遂昌县| 仙游县| 海兴县| 黎川县| 南投县| 和平县| 锡林浩特市| 巫溪县| 瓦房店市| 宁乡县| 麟游县| 鄢陵县| 宝鸡市| 周至县| 道真| 杭锦后旗| 安乡县| 综艺| 巨野县| 红河县| 尼勒克县| 京山县| 平凉市| 温宿县| 紫阳县| 耒阳市| 赣榆县| 无为县| 随州市| 博客| 乐亭县| 囊谦县| 天等县| 宁陵县| 福建省| 宁波市| 泰顺县|