KnockoutJS — Templating/Components.

Arun Raj R
2 min readFeb 14, 2017

--

  1. Template is a set of DOM elements which can be used repetitively.
  2. Templating makes it easy to build complex applications due to its property of minimizing duplication of DOM elements.
  3. Components are a huge way of organizing the sophisticated UI code for large applications and promote code re-usability.

The main idea is that we can separate both the HTML elements and viewmodels(Can even separate as different files). In this way we can reuse them.

Consider the below Example-1: take a look at this fiddle.

Example without components.

In the HTML there is a <select> element for dropdown list and there is a ‘data-bind’ attribute in the <select> with some couple of Binding element’s inside such as,

  1. options’ — For hold the values in dropdown.
  2. optionsCaption’ — For default text in dropdown.
  3. optionsText’ — For displaying the data.

In the JAVASCRIPT there is a sample json payload (sampleJson) and it contain some datas. Inside this viewmodel(myViewModel) there is a KO variable(aviliableNames) for holding the data’s.
ko.toJS() is a built-in method used to convert the json to the corresponding KO value. Now the data is in KO variable, So it will display the name in dropdown when we apply the bindings ‘ko.applyBindings();’

Consider the below Example-2: take a look at this fiddle.

Example with components.

The Example-2 follows the same functionality and behavior that i have done in Example-1. The only change is for the structuring because of the KnockoutJS Components.By using this KO components i can able to separate the HTML and viewmodel. The viewmodel is same as the Example-1 follows and HTML have less code compare to the Example-1. The only thing is we need to add a Binding element(component) for integrating both the HTML and viewmodel together. The all other HTML codes are assigned to a new variable (template) as a string . For registering this component we need to call ko.components.register() API. After applying the bindings ko.applyBindings() the data will display in the dropdown as same as in the Example-1.

Syntax for registering the Components:
ko.components.register(‘component-name’, {
viewModel: {…}, //function code
template: {….) //function code
});

. The component-name can be any nonempty string.

. viewmodel is optional, and can take any of the viewmodel formats.

. template is required, and can take any of the template formats.

So far, I’ve exposed facts about components. However, in this last section, I must say that in most situations I prefer to use components for their advantages:

.modularity
.low coupling
.easy reuse
.testability
.binding syntax

--

--

Arun Raj R
Arun Raj R

Written by Arun Raj R

I’m a Full-stack Developer, Mentor, and Consultant. https://arunraj.dev/

No responses yet