In this post we will take a look on Knockout.js. We will start with basic theoretical introduction and then to some basic demo on Knockout.js
Essentially Knockout.js helps to link a Data Model to UI. It tracks the changes and dynamically updates the UI. It helps to perform two ways binding in between UI and Data Model. It updates certain section of UI dynamically when data in data model is changed. It simplifies the task of binding and dynamic updating the UI.
Some of the features of Knockout.js can be outlined as below,
- It detects the data changes in data model and updates respective part of the UI.
- It binds data and UI declaratively. In other words declarative binding between data model and UI can be done using Knockout.js
- It helps to create custom behavior. Custom behavior can be created as declarative binding.
- Custom behavior created by Knockout.js can be reused with very less lines of code.
- It helps to create complex dynamic UI using declarative bindings.
Further in the post, we will explore each features of Knockout.js. You can download Knockout.js from here. You will get many versions of Knockout.js to download on the download page. For usual production purpose you can choose to download knockout-versionnumber.js file.
After downloading add reference of Knockout.js. Reference can be added as following,
Once you have created ViewModel you need to apply binding. Binding can be applied as below,
Last step is to bind values from ViewModel on the view. That can be done as following. Using data-bind attribute values from ViewModel can be bind to element on View.
A complete example of Product ViewModel data being bind with elements of View is given below,
And as expected you will get values from ViewModel on View elements as following
This was small introduction of Knockout.js. In further posts we will get into more details of Knockout.js and see examples of its usage in real examples. I hope you find this post useful. Thanks for reading