26 Feb

Templated Components with Knockout Continued

As promised in my last post, I am going to explain today how to write more complex templated components. I have already mentioned our dilemma with table components and that we wanted to use templates to solve it. When creating a table component, we want to be able to pass markup for the table header as well as for the table rows. So we need a way to define different parts of the template and to decide which parts to insert at which places into the component.

Defining Different Parts of the Template

For passing multiple parts of template into the component, we decided to place each part of the template in its own template tag. In order to distinguish between the roles of the different template parts, we use the ‘data-template-function’ attribute. In this example, ‘data-template-function’ can have the values ‘table-header’ or ‘table-row’. So this is the markup that is passed to the templated-table component:

Accessing the Template in the Viewmodel

In the templated list example from the last blog post, the template could be injected into the component directly by using $componentTemplateNodes. This won’t work here because the template consists of multiple parts which we wish to use in different places within the component. So the template needs to be processed by the component’s viewmodel first.

The component’s viewmodel can access the template via componentInfo.templateNodes, an array which contains all the DOM nodes of the template (as a reminder: componentInfo is passed to the component’s createViewModel function). The viewmodel should provide a parameter of the type HTMLElement[] for each template view element (important, it needs to be an array!). In this example, we use the variables tableHeader and tableRow. With the help of our data-template-function attribute, we can decide which value to assign to which variable:

Inserting the Template into the View

Once set in the viewmodel, the nodes can be inserted into the html at the correct place:

Templated Components are Awesome!

We have been using templated components for some time now. Every time I reuse one of them, I am very happy to see how little effort is needed to integrate it into the code. Templated components have really save us a lot of time and lines of code!

Share this

Leave a reply