Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have nested knockout components in javascript

I want something like this:

<base-component>
    <sec-component>
    </sec-component>
</base-component>

Is it possible to achieve this with the help of knockout components?

like image 590
s3e3 Avatar asked Mar 03 '15 08:03

s3e3


1 Answers

Yes. In the documentation, "Passing markup into components" section: http://knockoutjs.com/documentation/component-custom-elements.html#passing-markup-into-components

<!-- This could be in a separate file -->
<template id="my-special-list-template">
    <h3>Here is a special list</h3>

    <ul data-bind="foreach: { data: myItems, as: 'myItem' }">
        <li>
            <h4>Here is another one of my special items</h4>
            <!-- ko template: { nodes: $componentTemplateNodes, data: myItem } --><!-- /ko -->
        </li>
    </ul>
</template>

<my-special-list params="items: someArrayOfPeople">
    <!-- Look, I'm putting markup inside a custom element -->
    The person <em data-bind="text: name"></em>
    is <em data-bind="text: age"></em> years old.
</my-special-list>

In the ko template inside the li element, the nodes will be added.

Therefore, you can also insert a different component in the inner markup. For example:

<!-- This could be in a separate file -->
<template id="my-special-list-template">
    <h3>Here is a special list</h3>

    <ul data-bind="foreach: { data: myItems, as: 'myItem' }">
        <li>
            <h4>Here is another one of my special items</h4>
            <!-- ko template: { nodes: $componentTemplateNodes, data: myItem } --><!-- /ko -->
        </li>
    </ul>
</template>

<template id="my-person-template">
    The person <em data-bind="text: name"></em>
    is <em data-bind="text: age"></em> years old.
</template>

<my-special-list params="items: someArrayOfPeople">
    <my-person></my-person>
</my-special-list>
like image 131
Guilherme Rodrigues Avatar answered Nov 15 '22 09:11

Guilherme Rodrigues