Develop Dynamic Client Side Application with KnockoutJS

Develop Dynamic Client Side Application with KnockoutJS

Posted in by Tudipat 07:09Comments Off on Develop Dynamic Client Side Application with KnockoutJS

Piyush Yadav

1 September, 2017

About Knockout.js

KnockoutJS is a JavaScript library that allows you to create dynamic and rich web applications. It makes it very simple to enact a complicated UI that responds to user interactions. It offers observables to sync UI with its data model along with set of declarative bindings.

KnockoutJS is built with the Model-View-View-Model (MVVM) pattern.

Knockout uses three things for implementation

View, that contains HTML and CSS elements that get data-bound to it.

ViewModel, contains the data to bind to the view.

Binding, data to the view with the ViewModel

Data Binding Syntax

In knockout we can bind data using an HTML attribute called data-bind to any HTML element that you want Knockout to replace with information from your viewModel.

There are two approaches to this:

Knockout allows you to specify data bindings with HTML comments Ex:

<!-- ko -->
<!-- /ko -->

If you want to wrap your binding around a block of HTML code then binding through HTML comments is extremely convenient.

It also allows us to dynamically display data(text or HTML) based on data present within a viewModel. Ex.

When you will executed this snippet, it will write Hello Mark Watney inside an h1 tag. A span tag is data-bound to the fullname property of the viewModel. This is done by placing text: fullname inside the data-bind HTML attribute.

ViewModel

A view model is a pure-code representation of the data and operations on a UI. One of the most important thing that knockout uses is viewModel.

In the above example, it is named as viewModel that contains only a single variable name. Ex: If you’re implementing a personal details form, your view model would be an object holding all your details, and exposing methods to add and remove them.

You just need to declare any JavaScript object to add a viewModel in Knockout:

Telling knockout to bind data

Now the most important thing is tell the knockout to bind the data on the view to the viewModel. For this you need to call ko.applyBindings function with a View‐Model.

ko.applyBindings(personalDetailsViewModel);

Observables

Till now we have studied how to create a viewmodel and how to its properties through data binding. One of the key benefits of Knockout is that it update our UI automatically when there is some change in viewmodel.

To do this, we need to declare our model properties as observables which can automatically detect dependencies. Ex:

Length of the array: myObservableArray().length;
0th element of the array: myObservableArray().[0];

This is a simple overview of ‘How to get started with building dynamic application mainly for client side’. Using these basic features of Knockout.js, you can develop dynamic client side application with much ease.