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

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.

主站蜘蛛池模板: 灵石县| 三门峡市| 桐城市| 寿宁县| 新野县| 洪江市| 南郑县| 保山市| 太谷县| 鹤庆县| 瑞安市| 南郑县| 南召县| 涿州市| 邓州市| 平顶山市| 玉龙| 阿鲁科尔沁旗| 南汇区| 宾阳县| 晋宁县| 嫩江县| 应用必备| 南郑县| 普格县| 辽阳县| 凤台县| 游戏| 正蓝旗| 康马县| 新竹县| 依安县| 盘山县| 秦皇岛市| 塘沽区| 德昌县| 崇义县| 新田县| 安西县| 永靖县| 北京市|