19 Feb

Templated Components with Knockout

Templated Components

Some time ago I wrote about our best practices for creating components. Even though components have been a great relieve to us when developing new features, there have been limitations as to their flexibility and reusability. For example, when using a component for different tables, each of the tables needed to have more or less the same layout and the same number of columns. To a certain degree, we could adapt the tables with the help of boolean variables, but this did not exactly increase the readability and quality of our code. So we ended up creating a whole range of different table components, even though their basic logic was the same: they all needed to do sorting, scrolling, filtering, etc.

This was when we started to investigate and found out that Knockout now allows passing markup into components. Thus we can have the same logic for all tables but use completely different layouts for them.

Example: Templated List

Here is a very simple example of a templated lists. For passing template into the component, any html code can be placed inside the component’s custom html element:

The component can inject any template into its html by using the knockout template binding. The parameter ‘nodes’ specifies an array of DOM nodes that are to be used as a template, the ‘data’ parameter supplies the data for the template to render.

The html we placed between the component tags can be accessed via $componentTemplateNodes:

The resulting list looks like this:

Patients

  • Name: John Smith, birth date: 23.09.1952

  • Name: Jenny Smith, birth date: 14.02.1963

Since we do not only want to use the component for patients, but also for orders, we use the same component again in a different view, and pass different template this time:

So we get a completely different list:

Orders

  • Name: John Smith, address: 111 Kirby Corner Rd, Coventry CV4 8GL, status: open

  • Name: Jenny Smith, address: Waterside, Stratford-upon-Avon CV37 7LS, status: delivered

Having understood the principle of how templated components work, we can now move on to creating more complex templated components that inject different parts of template into different places in their view. I will explain in one of my next blog post how this can be done.

Share this

Leave a reply