Knockoutjs Tutorial
Knockoutjs Tutorial
Knockoutjs Tutorial
This tutorial covers most of the topics required for a basic understanding of KnockoutJS
and explains its various functionalities.
Audience
This tutorial is designed for software programmers who want to learn the basics of
KnockoutJS and its programming concepts in a simple and easy way. This tutorial will give
you enough understanding on the components of KnockoutJS with suitable examples.
Prerequisites
Before proceeding with this tutorial, you should have a basic understanding of HTML, CSS,
JavaScript, Document Object Model (DOM), and any text editor. As we are going to develop
web-based application using KnockoutJS, it will be good if you have an understanding on
how the Internet and web-based applications work.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at contact@tutorialspoint.com
i
KnockoutJS
Table of Contents
About the Tutorial .................................................................................................................................... i
Audience .................................................................................................................................................. i
Prerequisites ............................................................................................................................................ i
Architecture ............................................................................................................................................ 6
Architecture ............................................................................................................................................ 8
ii
KnockoutJS
Observations ......................................................................................................................................... 49
Observations ......................................................................................................................................... 56
Observations ......................................................................................................................................... 62
If Binding ............................................................................................................................................... 63
Observations ......................................................................................................................................... 65
Observations ......................................................................................................................................... 70
iii
KnockoutJS
Observations ......................................................................................................................................... 75
Observations ......................................................................................................................................... 79
Observations ......................................................................................................................................... 87
iv
KnockoutJS
v
1. KnockoutJS ─ Overview KnockoutJS
KnockoutJS is basically a library written in JavaScript, based on MVVM pattern that helps
developers build rich and responsive websites. The model separates the application's
Model (stored data), View (UI) and View Model (JavaScript Representation of model).
Features of KnockoutJS
Here is a list of some of the most prominent features of KnockoutJS:
Declarative Binding: HTML DOM elements are connected to the model through
data-bind attribute using a very simple syntax. It is made easy to achieve
responsiveness using this feature.
Automatic UI Refresh: Any changes made to view the model data are reflected
in the UI automatically and vice-versa. No need of writing extra code.
It is pure JavaScript Library and works with any web framework. It's not a
replacement of JQuery but can work as a supplement providing smart features.
Most important of all KnockoutJS is open source and hence free for use.
KnockoutJS is fully documented. The official site has full documentation including
API docs, live examples, and interactive tutorials.
1
2. KnockoutJS ─ Environment Setup KnockoutJS
It is very easy to use KnockoutJS. Simply refer the JavaScript file using <script> tag in
HTML pages.
You can download production build of Knockout.js from its official website:
A page as in the following image will be displayed. Click the download link and you
will get the latest knockout.js file.
Update the src attribute to match the location where the downloaded files are kept.
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-
3.1.0.js" type="text/javascript"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-
min.js" type="text/javascript"></script>
Note: In all the chapters for this tutorial, we have referred to CDN version of the
KnockoutJS library.
Example
KnockoutJS is based on Model-View-ViewModel (MVVM) pattern. We will study this pattern
in depth in chapter KnockoutJS - MVVM Framework. First let's take a look at a simple
example of KnockoutJS.
2
KnockoutJS
<!DOCTYPE html>
<head>
<title>KnockoutJS Simple Example</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
</head>
<body>
<!-- This is called "view" of HTML markup that defines the appearance of UI -->
<script>
<!-- This is called "viewmodel". This javascript section defines the data
and behavior of UI -->
function AppViewModel() {
this.firstString = ko.observable("Enter First String");
this.secondString = ko.observable("Enter Second String");
this.thirdString = ko.computed(function() {
return this.firstString() + " " + this.secondString();
}, this);
}
// Activates knockout.js
ko.applyBindings(new AppViewModel());
</script>
</body>
</html>
3
KnockoutJS
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"> </script>
We have two input boxes: First String and Second String. These 2 variables are
initialized with values Enter First String and Enter Second String respectively in
ViewModel.
This is how we are binding values from ViewModel to HTML elements using 'data-
bind' attribute in the body section.
ko.observable is a concept which keeps an eye on the value changes so that it can update
the underlying ViewModel data.
To understand this better, let's update the first input box to "Hello" and the second input
box to "TutorialsPoint". You will see the values are updated simultaneously. We will study
more about this concept in KnockoutJS - Observables chapter.
this.thirdString = ko.computed(function() {
return this.firstString() + " " + this.secondString();
}, this);
Next, we have computed function in viewmodel. This function derives the third string
based on 2 strings mentioned earlier. Thus, any updates made to these strings
automatically get reflected in this derived string. There is no need of writing an extra code
to accomplish this. This is just a simple example. We will study about this concept
in KnockoutJS - Computed Observables chapter.
4
KnockoutJS
Output
Save the above code as my_first_knockoutjs_program.html. Open this file in your
browser and you will see an output as the following.
Modify strings to "Hello" and "TutorialsPoint" and the output changes as follows.
5
3. KnockoutJS ─ Application KnockoutJS
KnockoutJS is widely used for Single Page Applications - A website created with the ability
to retrieve all necessary data dynamically with a single page load reducing server round
trips.
Architecture
View
View is nothing but user interface created using HTML elements and CSS styling.
You can bind HTML DOM elements to data model using KnockoutJS. It provides 2-way data
binding between View and ViewModel using 'data-bind' concept, which means any updates
done in the UI are reflected in the data model and any changes done in the data model
are reflected in the UI. One can create self-updating UI with the help of knockoutJS.
6
KnockoutJS
ViewModel
ViewModel is a JavaScript object, which contains necessary properties and functions to
represent data. View and ViewModel are connected together with declarative data-bind
concept used in HTML. This makes it easy to change HTML without changing ViewModel.
KnockoutJS takes care of automatic data refresh between them through the use of
Observables.
Synchronization of data is achieved through binding DOM elements to Data Model, first
using data-bind and then refreshing these 2 components through the use of Observables.
Dependency tracking is done automatically due to this synchronization of data. No extra
coding is required to achieve it. KnockoutJS allows to create direct connection between
the display and underlying data.
You can create your own bindings called as custom bindings for application specific
behaviors. This way Knockout gives direct control of how you want to transform your data
into HTML.
Model
Model is the domain data on the server and it gets manipulated as and when the request
is sent/received from ViewModel.
The data could be stored in database, cookie, or other form of persistent storage.
KnockoutJS does not worry about how it is stored. It is up to the programmer to
communicate between the stored data and KnockoutJS.
Most of the times, data is saved and loaded via an Ajax call.
7
4. KnockoutJS ─ MVVM Framework KnockoutJS
The view classes do not know that Model and ViewModel classes exists, also Model and
ViewModel does not know that View exists. Model is also unaware that ViewModel and
View exists.
Architecture
8
KnockoutJS
View
View is a Graphical User Interface created using markup language to represent data. View
binds to properties of a ViewModel through data-bind concept, which indirectly connects
to the model data. View need not be changed for any alteration done in ViewModel.
Changes made to data in ViewModel is automatically propagated in View due to binding.
Model
Model is domain data or business object, which holds real-time data. Model does not carry
behaviors. Behavior is mostly implemented in business logic.
ViewModel
ViewModel is the center place, where data from Model and View's display logic are bundled
together. ViewModel holds the dynamic state of data. There is an implicit binder in between
View and ViewModel to communicate with each other. This binding is inclusive of
declarative data and command binding. Synchronization of View and ViewModel is
achieved through this binding. Any change made in View is reflected in ViewModel, and
similarly any change in ViewModel gets automatically reflected in View. Existence of this
2-way binding mechanism is a key aspect of this MVVM pattern.
9
5. KnockoutJS ─ Observables KnockoutJS
As the name specifies, when you declare a ViewModel data/property as Observable, any
data modification each time automatically gets reflected at all places the data is used. This
also includes refreshing the related dependencies. KO takes care of these things and there
is no need to write extra code to achieve this.
Syntax
You just need to declare ViewModel property with function ko.observable() to make it
Observable.
this.property = ko.observable('value');
Example
Let's take a look at the following example which demonstrates the use of Observable.
<!DOCTYPE html>
<head>
<title>KnockoutJS Observable Example</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
</head>
<body>
<!-- This is called "view" of HTML markup that defines the appearance of UI -->
10
KnockoutJS
<script>
<!-- This is called "viewmodel". This javascript section defines the data
and behavior of UI -->
function AppViewModel() {
this.yourName = ko.observable("");
}
// Activates knockout.js
ko.applyBindings(new AppViewModel());
</script>
</body>
</html>
The following line is for the input box. As can be seen, we have used data-bind attribute
to bind yourName value to ViewModel.
The following line just prints the value of yourName. Note, that here data-bind type is the
text as we are simply reading the value.
In the following line, ko.observable keeps an eye on yourName variable for any
modification in data. Once there is a modification, the corresponding places also get
updated with the modified value. When you run the following code, an input box will
appear. As and when you update that input box, the new value will get reflected or
refreshed in places wherever it is used.
this.yourName = ko.observable("");
Output
Let's carry out the following steps to see how the above code works:
11
KnockoutJS
Data modification can take place either from the UI or from ViewModel. Irrespective of
from where the data is changed, the UI and ViewModel keeps synchronization among
them. This makes it a two-way-binding mechanism. In the above example, when you
change your name in the input box, ViewModel gets a new value. When you change
yourName property from inside ViewModel, then the UI receives a new value.
Sr.
Read/Write Operation & Syntax
No.
Read
1 To read value just call Observable property without parameters like:
AppViewModel.yourName();
Write
2
To write/update value in Observable property, just pass the desired value in
parameter like: AppViewModel.yourName('Bob');
Write multiple
3
Multiple ViewModel properties can be updated in a single row with the help of
chaining-syntax like: AppViewModel.yourName('Bob').yourAge(45);
Observable Arrays
Observable declaration takes care of data modifications of a single object. ObservableArray
works with the collection of objects. This is a very useful feature when you are dealing
with complex applications containing multiple type of values and changing their status
frequently based on the user actions.
12
KnockoutJS
Syntax
this.arrayName = ko.observableArray(); // It's an empty array
Observable array only tracks which objects in it are added or removed. It does not notify
if the individual object's properties are modified.
this.arrayName = ko.observableArray(['scott','jack']);
ObservableArray Functions
KnockoutJS has its own set of Observable array functions. They are convenient because:
Syntax is easy to use. For example, to insert an element into an array, you just
need to use arrayName.push('value') instead of arrayName().push('value').
Sr.
Methods & Description
No.
push('value')
1
Inserts a new item at the end of array.
pop()
2
Removes the last item from the array and returns it.
unshift('value')
3
Inserts a new value at the beginning of the array.
shift()
4
Removes the first item from the array and returns it.
reverse()
5
Reverses the order of the array.
13
KnockoutJS
sort()
6
Sorts array items in an ascending order.
splice(start-index,end-index)
7 Accepts 2 parameters - start-index and end-index - removes items starting from
start to end index and returns them as an array.
indexOf('value')
8
This function returns the index of the first occurrence of parameter provided.
slice(start-index,end-index)
9 This method slices out a piece of an array. Returns the items from start-index
up to end-index.
removeAll()
10
Removes all items and returns them as an array.
remove('value')
11
Removes items that match the parameter and returns as an array.
remove(function(item) { condition })
12
Removes items which are satisfying the condition and returns them as an array.
remove([set of values])
13
Removes items that match with a given set of values.
destroyAll()
14
Marks all items in an array with property _destroy with value true.
destroy('value')
15 Searches for an item equal to the parameter and mark it with a special property
_destroy with value true.
destroy(function(item) { condition})
16 Finds all items which are satisfying the condition, marks them with property
_destroy with true value.
destroy([set of values])
17 Finds the items that match with a given set of values, marks them as _destroy
with true value.
Note: Destroy and DestroyAll Functions from ObservableArrays are mostly for 'Ruby on
Rails' developers only.
When you use destroy method, the corresponding items are not really deleted from array
at that moment but are made hidden by marking them with
property _destroy with true value so that they can't be read by UI. Items marked
as _destroy equal to true are deleted later while dealing with JSON object graph.
14
KnockoutJS
push() Method
Description
The KnockoutJS Observable push('value') method inserts a new item at the end of an
array.
Syntax
arrayName.push('value')
Parameters
Accepts only one parameter, that is the value to be inserted.
Example
<!DOCTYPE html>
<head>
<title>KnockoutJS Observable Array push() Method</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
</head>
<body>
<p>Example to demonstrate push() method.</p>
<p>Enter name: <input data-bind='value: empName' /></p>
<p><button data-bind="click: addEmp">Add Emp </button></p>
<p>Array of employees: <span data-bind="text: empArray()" ></span></p>
<script>
function EmployeeModel(){
this.empName = ko.observable("");
this.chosenItem = ko.observableArray("");
this.empArray =
ko.observableArray(['Scott','James','Jordan','Lee','RoseMary','Kathie']);
//Initial Values
this.addEmp = function() {
if (this.empName() != "") {
this.empArray.push(this.empName()); //insert accepted value in array
this.empName("");
}
15
KnockoutJS
}.bind(this);
}/
var emp = new EmployeeModel();
ko.applyBindings(emp);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works:
pop() Method
Description
The KnockoutJS Observable pop() method removes the last item from an array and
returns it.
Syntax
arrayName.pop()
Parameters
Does not accept any parameters.
16
KnockoutJS
Example
<!DOCTYPE html>
<head>
<title>KnockoutJS ObservableArray pop method</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
</head>
<body>
<p>Example to demonstrate pop()method.</p>
<button data-bind="click: popEmp">Remove Emp</button>
<p>Array of employees: <span data-bind="text: empArray()" ></span></p>
<script>
function EmployeeModel(){
this.empName = ko.observable("");
this.chosenItem = ko.observableArray("");
this.empArray =
ko.observableArray(['Scott','James','Jordan','Lee','RoseMary','Kathie']);
this.popEmp = function() {
this.empArray.pop();
}
}
var em = new EmployeeModel();
ko.applyBindings(em);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works:
Click the Remove Emp button and observe that the last element is removed.
17
KnockoutJS
unshift() Method
Description
The KnockoutJS Observable unshift('value') method inserts a new item at the beginning
of the array.
Syntax
arrayName.unshift('value')
Parameters
Accepts one parameter, that is the value to be inserted.
Example
<!DOCTYPE html>
<head>
<title>KnockoutJS ObservableArray unshift method</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
</head>
<body>
<p>Example to demonstrate unshift() method.</p>
<p>Enter name: <input data-bind='value: empName' /></p>
<button data-bind="click: unshiftEmp">Add Emp in Beginning</button><br><br>
<p>Array of employees: <span data-bind="text: empArray()" ></span></p>
<script>
18
KnockoutJS
function EmployeeModel(){
this.empName = ko.observable("");
this.chosenItem = ko.observableArray("");
this.empArray =
ko.observableArray(['Scott','James','Jordan','Lee','RoseMary','Kathie']);
this.unshiftEmp = function() {
if (this.empName() != "") {
this.empArray.unshift(this.empName()); // insert at the beginning
this.empName("");
}
}.bind(this);
}
var em = new EmployeeModel();
ko.applyBindings(em);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works:
19
KnockoutJS
shift() Method
Description
The KnockoutJS Observable shift() method removes the first item from the array and
returns it.
Syntax
arrayName.shift()
Parameters
Does not accept any parameter.
Example
<!DOCTYPE html>
<head>
<title>KnockoutJS ObservableArray shift method</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
</head>
<body>
<p>Example to demonstrate shift() method.</p>
<button data-bind="click: shiftEmp">Remove First Emp</button>
<p>Array of employees: <span data-bind="text: empArray()" ></span></p>
<script>
function EmployeeModel(){
this.empName = ko.observable("");
this.chosenItem = ko.observableArray("");
this.empArray =
ko.observableArray(['Scott','James','Jordan','Lee','RoseMary','Kathie']);
this.shiftEmp = function() {
this.empArray.shift(); //remove first item
}
}
var em = new EmployeeModel();
20
KnockoutJS
ko.applyBindings(em);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works:
reverse() Method
Description
The KnockoutJS Observable reverse() method reverses the order of the array.
Syntax
arrayName.reverse()
Parameters
Does not accept any parameter.
Example
<!DOCTYPE html>
<head>
<title>KnockoutJS ObservableArray reverse method</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
21
KnockoutJS
</head>
<body>
<p>Example to demonstrate reverse() method.</p>
<button data-bind="click: revEmp">Reverse Array</button>
<p>Array of employees: <span data-bind="text: empArray()" ></span></p>
<script>
function EmployeeModel(){
this.empName = ko.observable("");
this.chosenItem = ko.observableArray("");
this.empArray =
ko.observableArray(['Scott','James','Jordan','Lee','RoseMary','Kathie']);
this.revEmp = function() {
this.empArray.reverse(); // reverse order
}
}
var em = new EmployeeModel();
ko.applyBindings(em);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works:
22
KnockoutJS
sort() Method
Description
The KnockoutJS Observable sort() method sorts all items in the array.
By default, items are sorted in an ascending order. For sorting an array in a descending
order, use reverse() method on sorted array.
Syntax
arrayName.sort()
Parameters
Does not accept any parameter.
Example
<!DOCTYPE html>
<head>
<title>KnockoutJS ObservableArray sort method</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
</head>
<body>
<p>Example to demonstrate sort() method.</p>
<button data-bind="click: sortEmp">Sort Array</button>
<p>Array of employees: <span data-bind="text: empArray()" ></span></p>
<script>
23
KnockoutJS
function EmployeeModel(){
this.empName = ko.observable("");
this.chosenItem = ko.observableArray("");
this.empArray =
ko.observableArray(['Scott','James','Jordan','Lee','RoseMary','Kathie']);
this.sortEmp = function() {
this.empArray.sort(); //sort array
}
}
var em = new EmployeeModel();
ko.applyBindings(em);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works:
splice() Method
Description
The KnockoutJS Observable splice() method takes 2 parameters specifying the start-
index and the end-index. It removes items starting from start to end index and returns
them as an array.
24
KnockoutJS
Syntax
arrayName.splice(start-index,end-index)
Parameters
Accepts 2 parameters, start-index is start index and end-index is end index.
Example
<!DOCTYPE html>
<head>
<title>KnockoutJS ObservableArray splice method</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
</head>
<body>
<p>Example to demonstrate splice() method.</p>
<button data-bind="click: spliceEmp">Splice Emp</button>
<p>Array of employees: <span data-bind="text: empArray()" ></span></p>
<script>
function EmployeeModel(){
this.empName = ko.observable("");
this.chosenItem = ko.observableArray("");
this.empArray =
ko.observableArray(['Scott','James','Jordan','Lee','RoseMary','Kathie']);
this.spliceEmp = function() {
alert("Splice is removing items from index 1 to 3(If exists).");
this.empArray.splice(1,3); // remove 2nd,3rd and 4th item, as array
index starts with 0.
}
}
var em = new EmployeeModel();
ko.applyBindings(em);
</script>
</body>
</html>
25
KnockoutJS
Output
Let's carry out the following steps to see how the above code works:
indexOf() Method
Description
The KnockoutJS Observable indexOf('value') method returns the index of the first
occurrence of the parameter provided. This function will return -1, if no matching element
is found.
Syntax
arrayName.indexOf('value')
Parameters
Accepts 1 parameter, whose index will be returned.
Example
<!DOCTYPE html>
<head>
<title>KnockoutJS ObservableArray indexOf method</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
</head>
26
KnockoutJS
<body>
<p>Example to demonstrate indexOf() method.</p>
<p>Index of Employee 'Jordan':<span data-bind="text:
empArray().indexOf('Jordan')"></span ></p>
<p>Array of employees: <span data-bind="text: empArray()" ></span></p>
<script>
function EmployeeModel(){
this.empName = ko.observable("");
this.chosenItem = ko.observableArray("");
this.empArray =
ko.observableArray(['Scott','James','Jordan','Lee','RoseMary','Kathie']);
}
var em = new EmployeeModel();
ko.applyBindings(em);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works:
27
KnockoutJS
slice() Method
Description
The KnockoutJS Observable slice() method slices out a piece of an array. Slice here is the
same as native JavaScript slice function. Returns the elements from start-index up to end-
index.
Syntax
arrayName.slice(start-index,end-index)
Parameters
Accepts 2 parameters, start-index and end-index.
Example
<!DOCTYPE html>
<head>
<title>KnockoutJS ObservableArray slice method</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
</head>
<body>
<p>Example to demonstrate slice() method.</p>
<p>slice(1,3) to show items starting from index 1 up to 3:<span data-
bind="text: empArray().slice(1,3)"></span ></p>
<p>Array of employees: <span data-bind="text: empArray()" ></span></p>
<script>
function EmployeeModel(){
this.empName = ko.observable("");
this.chosenItem = ko.observableArray("");
this.empArray =
ko.observableArray(['Scott','James','Jordan','Lee','RoseMary','Kathie']);
}
var em = new EmployeeModel();
ko.applyBindings(em);
</script>
</body>
28
KnockoutJS
</html>
Output
Let's carry out the following steps to see how the above code works:
removeAll() Method
Description
The KnockoutJS Observable removeAll() method removes all items and returns them as
an array.
Syntax
arrayName.removeAll()
Parameters
Does not accept any parameter.
Example
<!DOCTYPE html>
<head>
<title>KnockoutJS ObservableArray removeAll method</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
</head>
<body>
29
KnockoutJS
<script>
function EmployeeModel(){
this.empName = ko.observable("");
this.chosenItem = ko.observableArray("");
this.empArray =
ko.observableArray(['Scott','James','Jordan','Lee','RoseMary','Kathie']);
this.removeallEmp = function() {
this.empArray.removeAll();
}
}
var em = new EmployeeModel();
ko.applyBindings(em);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works:
30
KnockoutJS
remove() Method
Description
The KnockoutJS Observable remove('value') method removes the items matching with
the 'value' and returns as an array.
Syntax
arrayName.remove('value')
Parameters
Accepts one parameter as a value to be removed.
Example
<!DOCTYPE html>
<head>
<title>KnockoutJS ObservableArray remove method</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
</head>
<body>
<p>Example to demonstrate remove() method.</p>
<button data-bind="click: removeEmp">Remove selected Emp</button>
<p>Array of employees:</p>
<select multiple="true" size="8" data-bind="options: empArray ,
selectedOptions: chosenItem"> </select>
<script>
function EmployeeModel(){
this.empName = ko.observable("");
this.chosenItem = ko.observableArray("");
this.empArray =
ko.observableArray(['Scott','James','Jordan','Lee','RoseMary','Kathie']);
this.removeEmp = function(chosenItem) {
if (this.chosenItem().length == 0) {
alert("Please select item/s to be removed.");
}
31
KnockoutJS
while(this.chosenItem().length > 0) {
this.empArray.remove(this.chosenItem()[0]);
}
}
}
var em = new EmployeeModel();
ko.applyBindings(em);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works:
Description
The KnockoutJS Observable remove(function(item) { return condition })method
removes the items which are satisfying a condition and returns them as an array.
Syntax
32
KnockoutJS
Parameters
This method accepts a parameter in the form of a function having a condition. Items from
an array satisfying the mentioned condition are removed.
Example
<!DOCTYPE html>
<head>
<title>KnockoutJS ObservableArray function based remove method</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
</head>
<body>
<p>Example to demonstrate function based remove() method.</p>
<button data-bind="click: removeoncondEmp">Remove on condition</button>
<p>Array of employees: <span data-bind="text: empArray()" ></span></p>
<script>
function EmployeeModel(){
this.empName = ko.observable("");
this.chosenItem = ko.observableArray("");
this.empArray =
ko.observableArray(['Scott','James','Jordan','Lee','RoseMary','Kathie']);
this.removeoncondEmp = function() {
alert("This function is removing items whos value is 'James'.");
this.empArray.remove(function (empName) { return empName ===
'James' }); //remove where empName is James
}
}
var em = new EmployeeModel();
ko.applyBindings(em);
</script>
</body>
</html>
Output
33
KnockoutJS
Let's carry out the following steps to see how the above code works:
Description
The KnockoutJS Observable remove([set of values]) method removes the items that
match a given set of values.
Syntax
arrayName.remove([set of values])
Parameters
This method accepts a parameter in the form of a values set.
Example
<!DOCTYPE html>
<head>
<title>KnockoutJS ObservableArray remove multiple method</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
</head>
<body>
<p>Example to demonstrate remove([set of values]) method.</p>
<button data-bind="click: removemultiEmp">Remove multiple Emps</button>
<p>Array of employees: <span data-bind="text: empArray()" ></span></p>
34
KnockoutJS
<script>
function EmployeeModel(){
this.empName = ko.observable("");
this.chosenItem = ko.observableArray("");
this.empArray =
ko.observableArray(['Scott','James','Jordan','Lee','RoseMary','Kathie']);
this.removemultiEmp = function() {
alert("This function is removing multiple matching items
e.g.['RoseMary','Lee'].");
this.empArray.removeAll(['RoseMary','Lee']);
}
}
var em = new EmployeeModel();
ko.applyBindings(em);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works:
35
6. KnockoutJS ─ Computed ObservablesKnockoutJS
Syntax
this.varName = ko.computed(function(){
...
... // function code
...
},this);
Example
Let us look at the following example which demonstrates the use of Computed
Observables.
<!DOCTYPE html>
<head >
<title>KnockoutJS Computed Observables</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-
3.1.0.js"></script>
</head>
<body>
<script>
function MyViewModel() {
this.a = ko.observable(10);
this.b = ko.observable(40);
this.totalAvg = ko.computed(function(){
if(typeof(this.a()) !== "number" || typeof(this.b()) !== "number"){
36
KnockoutJS
</script>
</body>
</html>
In the following lines, first two are for accepting input values. Third line prints the average
of these two numbers.
In the following lines, type of Observables a and b is number when they are initialized for
the first time inside ViewModel. However, in KO every input accepted from UI is by default
in the String format. So they need to be converted to Number so as to perform arithmetic
operation on them.
this.totalAvg = ko.computed(function(){
if(typeof(this.a()) !== "number" || typeof(this.b()) !== "number"){
this.a(Number(this.a())); //convert string to Number
this.b(Number(this.b())); //convert string to Number
}
total = (this.a() + this.b())/2 ;
return total;
},this);
In the following line, the calculated average is displayed in the UI. Note that data-bind
type of totalAvg is just text.
37
KnockoutJS
Output
Let's carry out the following steps to see how the above code works:
Managing 'This'
Note that in the above example, the second parameter is provided as this to Computed
function. It is not possible to refer to Observables a() and b() without providing this.
To overcome this, self variable is used which holds the reference of this. Doing so, there
is no need to track this throughout the code. Instead, self can be used.
Following ViewModel code is rewritten for the above example using self.
function MyViewModel(){
self = this;
self.a = ko.observable(10);
self.b = ko.observable(40);
this.totalAvg = ko.computed(function(){
if(typeof(self.a()) !== "number" || typeof(self.b()) !== "number"){
self.a(Number(self.a())); //convert string to Number
self.b(Number(self.b())); //convert string to Number
}
total = (self.a() + self.b())/2 ;
return total;
});
}
38
KnockoutJS
You can make Computed Observables always explicitly notify the observers, even though
the new value is the same as the old by using the notify syntax as follows.
myViewModel.property = ko.pureComputed(function() {
return ...; // code logic goes here
}).extend({ notify: 'always' });
// make sure there are updates no more than once per 100-millisecond period
myViewModel.property.extend({ rateLimit: 100 });
Sr.
Function
No.
ko.isComputed
1
Returns true if the property is Computed Observable.
ko.isObservable
2 Returns true if the property is Observable, Observable array, or Computed
Observable.
ko.isWritableObservable
3 Returns true if Observable, Observable array, or Writable Computed
Observable. (This is also called as ko.isWriteableObservable)
39
KnockoutJS
These writable Computed Observables work just like regular Observables. In addition, they
require custom logic to be built for interfering read and write actions.
One can assign values to many Observables or Computed Observable properties using the
chaining syntax as follows.
myViewModel.fullName('Tom Smith').age(45)
Example
Following example demonstrates the use of Writable Computable Observable.
<!DOCTYPE html>
<head >
<title>KnockoutJS Writable Computed Observable</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"></script>
</head>
<body>
<p>Enter your birth Date: <input type="date" data-bind="value: rawDate" > </p>
<p> <span data-bind="text: yourAge"></span></p>
<script>
function MyViewModel(){
this.yourAge = ko.observable();
today = new Date();
rawDate = ko.observable();
this.rawDate = ko.pureComputed({
read: function(){
return this.yourAge;
},
write: function(value){
var b = Date.parse(value); // convert birth date into milliseconds
var t = Date.parse(today); // convert todays date into milliseconds
diff = t - b; // take difference
40
KnockoutJS
var y = Math.floor(diff/31449600000);
// difference is converted into years. 31449600000 milliseconds form a year.
</script>
</body>
</html>
In the above code, rawDate is pureComputed property accepted from UI. yourAge
Observable is derived from rawDate.
Dates in JavaScript are manipulated in milliseconds. Hence, both the dates (today date
and birth date) are converted into milliseconds and then the difference between them is
converted back in years and months.
Output
Let's carry out the following steps to see how the above code works:
41
7. KnockoutJS ─ Declarative Bindings KnockoutJS
Without Observable, the property from the UI will be processed only for the first time. In
this case, it cannot update automatically based on the underlying data update. To achieve
this, bindings must be referred to Observable properties.
Binding Syntax
The binding consists of 2 items, the binding name and value. Following is a simple
example:
Here, text is the binding name and whatDay is the binding value. You can have multiple
bindings separated by comma, as shown in the following syntax.
Binding Values
The binding value can be a single value, literal, a variable or can be a JavaScript
expression. If the binding refers to some invalid expression or reference, then KO will
produce an error and stop processing the binding.
42
KnockoutJS
Starting from KO 3.0, you can skip the binding value which will give binding an
undefined value.
Binding Context
The data that is being used in current bindings can be referenced by an object. This object
is called binding context.
Sr.
Binding Context Types & Description
No.
$root
1 This always refers to top level ViewModel. This makes it possible to access top
level methods for manipulating ViewModel. This is usually the object, which is
passed to ko.applyBindings.
$data
2
This property is lot like this keyword in Javascript object. $data property in a
binding context refers to ViewModel object for the current context.
$index
This property contains index of a current item of an array inside a foreach loop.
3
The value of $index will change automatically as and when the underlying
Observable array is updated. Obviously, this context is available only
for foreach bindings.
$parent
4
This property refers to parent ViewModel object. This is useful when you want
to access outer ViewModel properties from inside of a nested loop.
$parentContext
43
KnockoutJS
$rawdata
This context holds raw ViewModel value in the current situation. This resembles
6
$data but the difference is, if ViewModel is wrapped in Observable, then $data
becomes just unwrapped. ViewModel and $rawdata becomes actual
Observable data.
$component
7 This context is used to refer to ViewModel of that component, when you are
inside a particular component. E.g. you might want to access some property
from ViewModel instead of current data in the template section of component.
$componentTemplateNodes
Following terms are also available in binding but are not actually binding context.
visible: <binding-condition>
1
To show or hide HTML DOM element depending on certain conditions.
text: <binding-value>
2
To set the content of an HTML DOM element.
html: <binding-value>
3
To set the HTML markup contents of a DOM element.
css: <binding-object>
4
To apply CSS classes to an element.
style: <binding-object>
5
To define the inline style attribute of an element.
44
KnockoutJS
attr: <binding-object>
6
To add attributes to an element dynamically.
Visible Binding
As the name specifies, this binding causes the associated DOM element to be visible or
hidden based on the value passed in the binding.
Syntax
visible: <binding-condition>
Parameters
When the parameter transforms into false-like value (such as boolean false, or 0,
or null, or undefined), then the binding sets display:none for
yourElement.style.display making it hidden. This is given more priority over any
existing styles in CSS.
When the parameter transforms into true-like value (such as boolean true,or non-
null object or array ), the binding removes yourElement.style.display value,
making it visible.
If this is an observable property, then the binding will update visibility every time
the property changes. Else, it will just set the visibility once.
Example
Let us take a look at the following example.
<!DOCTYPE html>
<head>
<title>KnockoutJS Visible Binding</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
</head>
<body>
<div data-bind="visible: showMe">
You are seeing this line because showMe function is set to true.
45
KnockoutJS
</div>
<script>
function AppViewModel() {
this.showMe = ko.observable(false); // hidden initially
}
var vm = new AppViewModel();
ko.applyBindings(vm); // shown now
vm.showMe(true);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works:
Text Binding
Text binding causes the associated DOM element to display the text value of the
parameter. This is used in text-level DOM elements such as <span> or <em>. The text
binding accepts any data type and parses it into String before rendering it.
Syntax
text: <binding-value>
46
KnockoutJS
Parameters
KO sets the element's content to a text node with your parameter value. Any
previous content will be overwritten.
If the parameter is an observable, then the element value is updated whenever the
underlying property changes, else it is assigned only for the first time.
Example
Let us take a look at the following example which demonstrates the use of text binding.
<!DOCTYPE html>
<head>
<title>KnockoutJS text binding</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
</head>
<body>
<p data-bind="text: hiThere"></p>
<script>
function AppViewModel() {
this.hiThere = ko.observable("Hi TutorialsPoint !!!");
}
var vm = new AppViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
47
KnockoutJS
Output
Let's carry out the following steps to see how the above code works:
Example
Let us take a look at another example in which the text is derived using Computed
Observable.
<!DOCTYPE html>
<head>
<title>KnockoutJS text binding</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
</head>
<body>
<p>Your full Name is <span data-bind="text: fullName"></span></p>
<script>
function AppViewModel() {
this.firstName= ko.observable("John");
this.lastName= ko.observable("Smith");
48
KnockoutJS
}
var vm = new AppViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works:
Observations
HTML encoding
The text binding escapes HTML entities, meaning that it is possible to set any String value
without getting it injected. For example -
The above code will just print <strong>Hi TutorialsPoint !!!</strong> on the screen. It
will not make the text bold.
49
KnockoutJS
The <!--ko--> and <!--/ko--> comment works as start and end markers making it a
virtual syntax and binds the data as if it is a real container.
<!DOCTYPE html>
<head>
<title>KnockoutJS container less text binding</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
</head>
<body>
<p data-bind="text: hiThere"></p>
<select data-bind="foreach: items">
<option> <!--ko text: $data --><!--/ko--></option>
</select>
<script>
function AppViewModel() {
this.hiThere = ko.observable("Days of week !!!");
this.items =
(['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']);
}
var vm = new AppViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works:
50
KnockoutJS
HTML Binding
HTML binding causes the associated DOM element to display the HTML specified by the
parameter. This is very useful if you want to generate HTML markup dynamically.
Syntax
html: <binding-value>
Parameters
KnockoutJS sets DOM element's content to the parameter value provided. This
functionality is also available in JQuery. If JQuery is not available, then KO is used
to achieve this.
If the parameter is observable, then elements value is updated as and when the
underlying observable is changed. Element is processed only once, if
no observable is used.
Example
Let us take a look ath the following example which demonstrates the use of html binding.
<!DOCTYPE html>
<head>
<title>KnockoutJS Html binding</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
</head>
<body>
<p><span data-bind="html: welcomeMessgae "></span></p>
<script>
51
KnockoutJS
function AppViewModel() {
this.welcomeMessgae = ko.observable();
this.welcomeMessgae ("<strong>Welcome to TutorialsPoint !!! For free
online tutorials and courses click <a
href='http://tutorialspoint.com/'>here</a>.</strong>");
}
ko.applyBindings(new AppViewModel());
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works:
CSS Binding
This binding allows you to define CSS classes for the HTML DOM elements based on certain
condition. This is useful in case you need to highlight some data depending on a situation.
Syntax
css: <binding-object>
Parameters
In case of static CSS binding, the parameter can be in the form of JavaScript Object,
consisting of property and its value.
52
KnockoutJS
o Property here refers to CSS class to be applied and value can be Boolean
true, or false, or JavaScript expression or a function.
Multiple CSS classes can also be applied at once. Following is an example of how 2
classes are added to binding.
Class names can also be specified in single quotes such as 'discount Available'.
0 and null are treated as false value. Numbers and other objects are treated
as true value.
Example
Let us take a look at the following example which demonstrates the use of CSS binding.
<!DOCTYPE html>
<head>
<title>KnockoutJS CSS binding</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
<style>
.outOfStock {
color: red;
font-weight: bold;
}
</style>
</head>
<body>
<div data-bind="css: { outOfStock : productStock() === 0 }">
Product Details.
</div>
<script>
function AppViewModel() {
53
KnockoutJS
this.productStock = ko.observable(0);
}
var vm = new AppViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works:
Style Binding
Style Binding allows you to apply inline styling to HTML DOM element by manipulating the
element's style attribute instead of applying CSS classes. This binding requires key-value
pair due to inline styling.
Syntax
style: <binding-object>
54
KnockoutJS
Parameters
JavaScript object should be passed as a parameter in which the property name
refers to style attribute and values refer to the desired values to be applied on the
elements.
Multiple styles can also be applied at once. Suppose you have a discount property
in your ViewModel and you want to add that, then the code will look like the
following -
If the productStock is not available, then the font becomes red. Else, it becomes
blue. If the discount is set to true, then Product Details will become bold font. Else,
it will remain in normal font.
If the ViewModel property is observable, then styles are applied depending on the
new updated parameter value. If it is not an observable value, then style is applied
only once for the first time.
Example
Let us take a look at the following example which demonstrates the use of style Binding.
<!DOCTYPE html>
<head>
<title>KnockoutJS style binding</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
</head>
<body>
<div data-bind="style: { color: productStock() < 0 ? 'red' : 'black' }">
Product Details.
</div>
<script type="text/javascript">
function AppViewModel() {
this.productStock= ko.observable(30000) // initially black as positive value
this.productStock(-10); // now changes DIV's contents to red
};
var vm = new AppViewModel();
ko.applyBindings(vm);
55
KnockoutJS
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works:
If productStock goes below 0, then Product Details becomes red. Else, if stock is
available it becomes black.
Observations
Click here for all JavaScript style attributes, which are also available at KO's official site.
Attr Binding
This binding allows you to dynamically assign HTML elements attribute using ViewModel
property. For example, you can set src attribute for an image, title attribute for HTML
page, or a href for a link in the tag based on values in ViewModel.
Syntax
attr: <binding-object>
56
KnockoutJS
Parameter
JavaScript object should be passed as a parameter in which the property name
refers to attribute name and values refer to the desired values to be passed to DOM
element.
Multiple attributes can also be assigned at once. Suppose you want to assign a
title and href a value, then binding will look like the following -
courseUrl and courseTitle variables will have the desired values in ViewModel.
Example
Let us take a look at the following example which demonstrates the use of Attr binding.
<!DOCTYPE html>
<head>
<title>KnockoutJS attribute binding</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
</head>
<body>
<a data-bind="attr: { href: courseUrl}">
Click here for free online tutorials and courses.
</a>
<script type="text/javascript">
function AppViewModel() {
this.courseUrl= ("http://tutorialspoint.com/");
};
var vm = new AppViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
57
KnockoutJS
Output
Let's carry out the following steps to see how the above code works:
Sr.
Binding Type & Usage
No.
foreach: <binding-array>
1
In this binding, each array item is referenced in HTML markup in a loop.
if: <binding-condition>
2 If the condition is true, then the given HTML markup will be processed. Else, it
will be removed from DOM.
ifnot: <binding-condition>
3 Negation of If. If the condition is true, then the given HTML markup will be
processed. Else, it will be removed from DOM.
with: <binding-object>
4 This binding is used to bind the child elements of an object in the specified
object's context.
58
KnockoutJS
Foreach Binding
In this binding, each array item is referenced in HTML markup in a loop. This is very useful
while populating a list or table data. foreach can be nested along with other control flow
bindings.
Syntax
foreach: <binding-array>
Parameters
Array name is passed as a parameter. HTML markup is processed for each item in
a loop.
A JavaScript object literal can be passed as a parameter and can be iterated over
using a property called data.
If the parameter is an observable one, then any modifications made are reflected
in the UI as soon as the underlying observable changes.
Example
Let us take a look at the following example, which demonstrates the use
of foreach binding.
<!DOCTYPE html>
<head>
<title>KnockoutJS foreach binding</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
</head>
<body>
<p>List of courses available:</p>
<div data-bind="foreach: courseArray ">
<li data-bind="text: $data"><span data-bind="text: $index"></span></li>
</div>
<script type="text/javascript">
function AppViewModel() {
this.courseArray = (['JavaScript','KnockoutJS','BackboneJS','EmberJS']);
this.courseArray.push('HTML');
};
59
KnockoutJS
Output
Let's carry out the following steps to see how the above code works:
You can rewrite the above code using as keyword. Just change the binding line as shown
in the following code.
Example
Let's take a look at another example to populate the list details using Observable Array.
<!DOCTYPE html>
<head>
<title>KnockoutJS foreach binding</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
</head>
<body>
60
KnockoutJS
<script type="text/javascript">
function AppViewModel() {
self=this;
self.productArray = ko.observableArray([
{productName: 'Milk'},
{productName: 'Oil'},
{productName: 'Shampoo'} ]);
self.removeProduct = function(){
self.productArray.remove(this);
}
};
var vm = new AppViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works:
61
KnockoutJS
Observations
<ul>
<!-- ko foreach: productArray -->
<li>
<span data-bind="text: productName"></span> <a href="#" data-bind="click:
$parent.removeProduct">Remove </a>
<!-- /ko -->
</li>
</ul>
The <!--ko--> and <!--/ko--> works as start and end markers making it a virtual syntax
and binds data as if it is a real container.
62
KnockoutJS
If Binding
This binding allows you to present the conditionally. If the specified condition is true, then
show data, else don't show.
if binding is similar to visible binding. Difference being, in visible binding the underlying
HTML markup actually stays on DOM and is made visible based on the condition whereas
in if binding, HTML markup is added or removed from DOM based on the condition.
Syntax
if: <binding-condition>
Parameters
Parameter is a condition you want to evaluate. If the condition evaluates
to true or true-like value, then the given HTML markup will be processed. Else, it
will be removed from DOM.
If the condition in the parameter contains an observable value, then the condition
is re-evaluated whenever the observable value changes. Correspondingly, related
markup will be added or removed based on the condition result.
Example
Let us take a look at the following example which demonstrates the use of if binding.
<!DOCTYPE html>
<head>
<title>KnockoutJS if binding</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
</head>
<body>
<p><strong>Product details</strong></p>
<table border="1">
<thead>
<th>Product Name</th><th>Price</th><th>Nature</th>
</thead>
<tbody data-bind="foreach: productArray ">
<tr>
<td><span data-bind="text: productName"></span></td>
<td><span data-bind="text: price"></span></td>
<td data-bind="if: $data.price > 100 ">Expensive</td>
63
KnockoutJS
</tr>
</tbody>
</table>
<script type="text/javascript">
function AppViewModel() {
self=this;
self.productArray = ko.observableArray([
{productName: 'Milk', price: 100},
{productName: 'Oil', price: 10},
{productName: 'Shampoo', price: 1200} ]);
};
var vm = new AppViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works:
This example will populate the third column which talks about the products’
nature (expensive or not) depending on the price. Note that the individual property
is accessed using $data binding context.
64
KnockoutJS
Observations
Container-less if
There might be a situation when it is not possible to place data-binding inside a DOM
element. Essential checking can still be performed with the help of container-less syntax
based on the comment tags shown as follows.
The <!--ko--> and <!--/ko--> works as start and end markers making it a virtual syntax
and binds the data as if it is a real container.
Example
Let's us take a look at the following example which demonstrates the use of container-less
syntax.
<!DOCTYPE html>
<head>
<title>KnockoutJS if binding</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
</head>
<body>
<ul>
<li>Monday</li>
<li>Tuesday</li>
<li>Wednesday</li>
<li>Thursday</li>
<li>Friday</li>
<!-- ko {if: weekend} -->
<li>Saturday - check if it is weekend.</li>
<li>Sunday</li>
<!-- /ko -->
</ul>
<script>
function AppViewModel() {
this.weekend = false;
}
var vm = new AppViewModel();
65
KnockoutJS
ko.applyBindings(vm);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works:
Ifnot Binding
Ifnot binding is the negating of if binding. It is just another flavor of if binding.
Syntax
ifnot: <binding-condition>
Parameters
Parameter is a condition you want to check. If the condition evaluates
to true or true-like value, then the given HTML markup will be processed. Else, it
will be removed from DOM.
If the condition in the parameter contains an observable value, then the condition
is re-evaluated whenever the observable value changes. Correspondingly, the
related markup will be added or removed based on the condition result.
Example
66
KnockoutJS
Let us take a look at the following example which demonstrates the use of ifnot binding.
<!DOCTYPE html>
<head>
<title>KnockoutJS ifnot binding</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
</head>
<body>
<p><strong>Product details</strong></p>
<table border="1">
<thead>
<th>Product Name</th><th>Price</th><th>Nature</th>
</thead>
<tbody data-bind="foreach: productArray ">
<tr>
<td><span data-bind="text: productName"></span></td>
<td><span data-bind="text: price"></span></td>
<td data-bind="ifnot: $data.price < 200 ">Expensive</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
function AppViewModel() {
self=this;
self.productArray = ko.observableArray([
{productName: 'Milk', price: 100},
{productName: 'Oil', price: 10},
{productName: 'Shampoo', price: 1200} ]);
};
var vm = new AppViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
Output
67
KnockoutJS
Let's carry out the following steps to see how the above code works:
This example will populate the third column which talks about the products’
nature (expensive or not) depending on the price. Note that the individual property
is accessed using $data binding context.
with Binding
This binding is used to bind the child elements of an object in the specified object's context.
This binding can also be nested with other type of bindings such as if and foreach.
Syntax
with: <binding-object>
Parameters
Pass the object which you want to use as context for binding child elements as the
parameter. Child elements will not be shown if the object or expression passed is
evaluated to be null or undefined.
Example
68
KnockoutJS
Let us take a look at the following example which demonstrates the use of with binding.
<!DOCTYPE html>
<head>
<title>KnockoutJS with binding</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
</head>
<body>
<h1 data-bind="text: siteName"> </h1>
<table border="1">
<thead>
<th>Course Name</th><th>Fees</th><th> Start Date</th>
</thead>
<tbody data-bind="with: courses ">
<tr>
<td><span data-bind="text: courseName"></span></td>
<td><span data-bind="text: Fees"></span></td>
<td><span data-bind="text: startDate"> </span></td>
</tr>
</tbody>
</table>
<script type="text/javascript">
function AppViewModel() {
self=this;
self.siteName =ko.observable( 'TutorialsPoint');
self.courses =ko.observable(
{courseName: 'Microsoft .Net', Fees: 20000, startDate: '20-Mar-2016'});
};
var vm = new AppViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
Output
69
KnockoutJS
Let's carry out the following steps to see how the above code works:
Observations
Container-less with
There might be a situation when it is not possible to place data-binding inside a DOM
element. Essential binding can still be performed with the help of container-less syntax
based on the comment tags as shown in the following code.
<ul>
<li>Course Info</li>
<!-- ko with: currentClasses -->
...
<!-- /ko -->
<!-- ko with: plannedClasses -->
...
<!-- /ko -->
</ul>
The <!--ko--> and <!--/ko--> works as start and end markers making it a virtual syntax
and binds the data as if it is a real container.
component Binding
This binding is used to insert a component into DOM elements and pass the parameters
optionally. This binding can be achieved in the following two ways:
70
KnockoutJS
Shorthand Syntax
Full syntax
Shorthand Syntax
In this approach only the component name is specified without specifying any parameters.
Syntax
<div data-bind='component: "component-name"'></div>
The parameter value passed can be an observable. Hence, whenever the observable
changes, the old component instance will be disposed and the new one will be created
according to the refreshed parameter value.
Full Syntax
This approach accepts the parameter in the form of an object.
Syntax
<div data-bind='component: {
name: "component-name",
params: { param1: value1, param2:value2 ...}
}'></div>
71
KnockoutJS
Receive ViewModel factory and template from component loaders - The registered
ViewModel and template is requested and received by the default loader. By default, this
is an asynchronous process.
Clone the component template - In this step, cloning of component template and
inserting it into DOM element takes place. Existing content, if any, will be removed.
new ViewModelName(params)
72
KnockoutJS
If the ViewModel is provided in factory function format, i.e. createViewModel then KO calls.
createViewModel(params, yourcomponentInfo)
Bind ViewModel to view - In this stage, ViewModel is bound to View. If the ViewModel
is not provided, then binding is done with parameters mentioned in component binding.
Now component is ready - At this stage, the component is ready and in functioning
form. The component keeps an eye on the parameters which are observable, if any, so as
to write the changed values.
Dispose the ViewModel if the component is lost - The ViewModel's dispose function
is called, if the component binding name value is changed observably or some control-flow
binding removes the DOM element container itself, which was meant to hold the
component output. The dispose takes place just before any element container is removed
from DOM.
Example
Let us take a look at the following example which demonstrates the use
of component binding.
<!DOCTYPE html>
<head>
<title>KnockoutJS Component binding</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type="text/javascript"></script>
</head>
<body>
<h4>Component binding without parameters</h4>
<div data-bind='component: "calculate-sum"'></div>
<script>
ko.components.register('calculate-sum', {
viewModel: function(params) {
this.number1 = ko.observable(params && params.number1);
73
KnockoutJS
this.result = ko.computed(function(){
var sum = Number(this.number1()) + Number(this.number2());
if ( isNaN(sum) )
sum = 0;
return sum;
},this);
},
template: 'Enter Number One: <input data-bind="value: number1" /> <br>
<br>'+
' Enter Number Two: <input data-bind="value: number2" /> <br> <br>'+
' Sum = <span data-bind="text: result" />'
});
ko.applyBindings();
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works:
74
KnockoutJS
Sum = 0
Sum = 5
Observations
ko.components.register('my-component', {
template: '<div data-bind="text: productName"></div>'
});
<div data-bind='component: {
name: "my-component",
params: { productName: someProduct.name }
}'></div>
The <!--ko--> and <!--/ko--> works as start and end markers making it a virtual syntax
and binds the data as if it is a real container.
75
KnockoutJS
unwanted objects, which are not garbage collectable by default. Following are a few
examples:
Sr.
Binding Type & Usage
No.
click: <binding-function>
1 This binding is used to invoke a JavaScript function associated with a DOM
element based on a click.
submit: <binding-function>
3 This binding is used to invoke a JavaScript function when the associated DOM
element is submitted.
enable: <binding-value>
4 This binding is used to enable certain DOM elements based on a specified
condition.
disable: <binding-value>
5 This binding disables the associated DOM element when the parameter
evaluates to true.
value: <binding-value>
6 This binding is used to link respective DOM element's value into ViewModel
property.
7 textInput: <binding-value>
76
KnockoutJS
This binding is used to create 2-way binding between text box or textarea and
ViewModel property.
hasFocus: <binding-value>
8 This binding is used to manually set the focus of a HTML DOM element through
a ViewModel property.
checked: <binding-value>
9 This binding is used to create a link between a checkable form element and
ViewModel property.
options: <binding-array>
10
This binding is used to define the options for a select element.
selectedOptions: <binding-array>
11 This binding is used to work with elements which are selected currently in multi
list select form control.
uniqueName: <binding-value>
12
This binding is used to generate a unique name for a DOM element.
Click Binding
Click binding is one of the simplest binding and is used to invoke a JavaScript function
associated with a DOM element based on a click. This binding works like an event handler.
This is most commonly used with elements such as button, input, and a, but actually
works with any visible DOM element.
Syntax
click: <binding-function>
Parameters
The parameter here will be a JavaScript function which needs to be invoked based on a
click. This can be any function and need not be a ViewModel function.
Example
Let us look at the following example which demonstrates the use of click binding.
<!DOCTYPE html>
77
KnockoutJS
<head>
<title>KnockoutJS Click Binding</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
function ViewModel (){
this.someValue = ko.observable();
this.showMessage = function(){
alert("Hello "+ this.someValue()+ "!!! How are you today?"+ "\nClick
Binding is used here !!!");
}
};
Output
Let's carry out the following steps to see how the above code works:
78
KnockoutJS
Observations
Example
Let us look at the following example to understand it better.
<!DOCTYPE html>
<head>
<title>KnockoutJS Click binding</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type="text/javascript"></script>
</head>
<body>
<p>List of product details:</p>
<ul data-bind="foreach: productArray ">
<li>
<span data-bind="text: productName"></span> <a href="#" data-
bind="click: $parent.removeProduct">Remove </a>
</li>
</ul>
<script type="text/javascript">
function AppViewModel() {
79
KnockoutJS
self=this;
self.productArray = ko.observableArray([
{productName: 'Milk'},
{productName: 'Oil'},
{productName: 'Shampoo'} ]);
self.removeProduct = function(){
self.productArray.remove(this);
}
};
var vm = new AppViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works:
removeProduct function is called every time the Remove link is clicked and is
called for that particular item in array.
Note that the $parent binding context is used to reach the handler function.
80
KnockoutJS
Example
Let us take a look at the following example to understand it better.
<!DOCTYPE html>
<head>
<title>KnockoutJS Click Binding</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
function ViewModel (){
this.showMessage = function(data,event){
alert("Click Binding is used here !!!");
if (event.ctrlKey) {
alert("User was pressing down the Control key.");
}
}
};
81
KnockoutJS
Output
Let's carry out the following steps to see how the above code works:
If you want the default action to take place in click binding, then you just need to
return true from your handler function.
Example
Let us look at the following example which demonstrates the default action performed
by click binding.
<!DOCTYPE html>
<head>
<title>KnockoutJS Click Binding - allowing default action</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type="text/javascript"></script>
</head>
<body>
82
KnockoutJS
</a>
<script type="text/javascript">
function ViewModel (){
this.callUrl = function(){
alert("Default action in Click Binding is allowed here !!! You are
redirected to link.");
return true;
}
};
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works:
Click the link and a message will be shown on the screen. The URL mentioned
in href opens in a new window.
83
KnockoutJS
Example
Let us look at the following example which demonstrates the use of clickBubble binding.
<!DOCTYPE html>
<head>
<title>KnockoutJS Click Binding - handling clickBubble</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
function ViewModel (){
this.outerFunction = function(){
alert("Handler function from Outer loop called.");
}
this.innerFunction = function(){
alert("Handler function from Inner loop called.");
}
};
var vm = new ViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
84
KnockoutJS
Output
Let's carry out the following steps to see how the above code works:
Click the button and observe that adding of clickBubble binding with
value false prevents the event from making it past innerFunction.
Event Binding
This binding is used to listen to specific DOM event and call associated with the handler
function based on it.
Syntax
event: <{DOM-event: handler-function}>
Parameters
Parameter is inclusive of a JavaScript object, containing DOM event which will be listened
to and a handler function which needs to be invoked based on that event. This function
can be any JavaScript function and need not be necessarily ViewModel function.
Example
Let us take a look at the following example which demonstrates the use of event binding.
<!DOCTYPE html>
<head>
<title>KnockoutJS Event Binding</title>
85
KnockoutJS
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type="text/javascript"></script>
</head>
<body>
<p>Enter Number :</p>
<input data-bind="value: someValue , event: {keyup: showMessage},
valueUpdate: 'afterkeydown' " /><br><br>
You Entered: <span data-bind="text: someValue"/>
<script type="text/javascript">
function ViewModel (){
this.someValue = ko.observable();
this.showMessage = function(data,event){
if ((event.keyCode < 47) || (event.keyCode > 58 )) { //check for number
if (event.keyCode !== 8) //ignore backspace
alert("Please enter a number.");
this.someValue('');
}
}
};
var vm = new ViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works:
86
KnockoutJS
Observations
Example
Let us take a look at the following example in which the current item is passed
in event binding.
<!DOCTYPE html>
<head>
<title>KnockoutJS Event Binding - passing current item </title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type="text/javascript"></script>
</head>
<body>
<ul data-bind="foreach: icecreams">
<li data-bind="text: $data, event: { mouseover: $parent.logMouseOver }">
</li>
</ul>
<p>You seem to be interested in: <span data-bind="text: flavorLiked">
</span></p>
<script type="text/javascript">
function ViewModel (){
var self=this;
87
KnockoutJS
self.flavorLiked = ko.observable();
self.icecreams = ko.observableArray(['Vanilla', 'Pista', 'Chocolate', 'Mango']);
Output
Let's carry out the following steps to see how the above code works:
Note that self as an alias is used for this. This helps to avoid any problems
with this being redefined to something else in event handlers.
88
KnockoutJS
Example
Let us take a look a the following example in which the event is sent as a second parameter
to function.
<!DOCTYPE html>
<head>
<title>KnockoutJS Event Binding - passing more params</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type="text/javascript"></script>
</head>
<body>
<div data-bind="event: { mouseover: logMouseOver }">
Press shiftKey + move cursor over this line.
</div>
<script type="text/javascript">
function ViewModel (){
self.logMouseOver = function (data, event) {
if (event.shiftKey){
alert("shift key is pressed.");
}
else {
alert("shift key is not pressed.");
}
}
};
var vm = new ViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
89
KnockoutJS
Output
Let's carry out the following steps to see how the above code works:
Press shiftKey + move cursor to the text. Observe that the message will pop up
showing if you have pressed the shiftKey.
If you want the event to perform a default action, then just return true from the handler
function.
Example
Let us look at the following example which allows default action to take place.
<!DOCTYPE html>
<head>
<title>KnockoutJS Event Binding - allowing default action</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type="text/javascript"></script>
</head>
<body>
<p>Enter the flavor you like from available menu: (Vanilla, Pista,
Chocolate, Mango)</p>
<input data-bind="event: { keypress: acceptInput}"></input>
90
KnockoutJS
<script type="text/javascript">
function ViewModel (){
self.acceptInput = function () {
return true;
}
};
var vm = new ViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works:
Any key pressed is actually shown in the input box because the handler function
returns true.
91
KnockoutJS
Example
Let us take a look at the following example in which bubbling is handled.
<!DOCTYPE html>
<head>
<title>KnockoutJS Event Binding - preventing bubbling </title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type="text/javascript"></script>
</head>
<body>
<div data-bind="event: { mouseover: myParentHandler }">
<button data-bind="event: { mouseover: myChildHandler }, mouseoverBubble:
false">
Click me to check bubbling.
</button>
</div>
<script type="text/javascript">
function ViewModel (){
var self= this;
self.myParentHandler = function () {
alert("Parent Function");
}
self.myChildHandler = function () {
alert("Child Function");
}
};
var vm = new ViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
92
KnockoutJS
Output
Let's carry out the following steps to see how the above code works:
Move the mouseover button and you will see a message. Bubbling is prevented due
to the use of mouseoverBubble set to false.
Submit Binding
This binding is used to invoke a JavaScript function when the associated DOM element is
submitted. This binding is used mostly for form elements.
The form is not actually submitted to the server when submit binding is used. KO prevents
browsers default action. If you want submit binding to work as real submit element, then
return true from your handler function.
Syntax
submit: <binding-function>
Parameters
The binding function here will be the main function which needs to be invoked after
submit event.
This function can be any JavaScript function and need not be necessarily ViewModel
function.
93
KnockoutJS
Example
Let us take a look at the following example which demonstrates the use of submit binding.
<!DOCTYPE html>
<head>
<title>KnockoutJS Submit Binding</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type="text/javascript"></script>
</head>
<body>
<form data-bind="submit: addition">
<p>Enter first number: <input data-bind="value: var1" /></p>
<p>Enter second number: <input data-bind="value: var2" /></p>
<p><button type="submit" >Click here for addition</button></p>
</form>
<script type="text/javascript">
function ViewModel (){
self = this;
self.var1 = ko.observable(10);
self.var2 = ko.observable(30);
self.var3 = ko.observable(0);
this.addition = function(){
self.var1(Number(self.var1()));
self.var2(Number(self.var2()));
this.var3 = self.var1() + self.var2();
alert("Addition is = "+ this.var3 );
};
};
94
KnockoutJS
Output
Let's carry out the following steps to see how the above code works:
This program adds 2 numbers. In KO, any accepted data from UI is considered in
String format by default. Hence, it needs to be converted to Number format in case
of Numeric operation.
Please refer to click binding for additional notes such as passing extra parameters, etc. All
notes on that page also apply to submit binding.
Enable Binding
This binding is used to enable certain DOM element based on specified condition. This is
useful with form elements such as input, select, and textarea.
Syntax
enable: <binding-value>
Parameters
Parameter consists of Boolean like value which decides whether the element should
be enabled or not. Element is enabled, if the parameter is true or true like value.
Non-Boolean values are considered as loosely Boolean values. Meaning 0 and null
are considered as false-like value, and Integer and non null objects are considered
as true-like value.
If the condition in the parameter contains any observable value, then the condition
is re-evaluated whenever observable value changes. Correspondingly, related
markup will be enabled based on the condition result.
95
KnockoutJS
Example
Let us take a look at the following example which demonstrates the use of enable binding.
<!DOCTYPE html>
<head>
<title>KnockoutJS Enable Binding</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
function ViewModel (){
hasFeedback = ko.observable('');
};
Output
Let's carry out the following steps to see how the above code works:
96
KnockoutJS
Example
Let us take a look at the following example which demonstrates the use of random
expression to invoke enable binding.
<!DOCTYPE html>
<head>
<title>KnockoutJS Enable binding</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type="text/javascript"></script>
</head>
<body>
<p>Below button will be enabled only when product stock is available.</p>
<button data-bind="enable: productStock() > 0 ">
Product Details
</button>
<script type="text/javascript">
function AppViewModel() {
this.productStock= ko.observable(-10);
};
var vm = new AppViewModel();
ko.applyBindings(vm);
97
KnockoutJS
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works:
Disable Binding
This binding is the negation of enable binding. This binding disables the associated DOM
element when the parameter evaluates to true.
Syntax
disable: <binding-value>
Parameters
Parameter consists of Boolean like value, which decides whether the element
should be disabled or not. If the parameter is true or true-like value, then the
element is disabled.
Non-Boolean values are considered as loosely Boolean values. Meaning 0 and null
are considered as false-like value and Integer and non-null objects are considered
as true-like value.
98
KnockoutJS
Example
Let us take a look at the following example which demonstrates the use of disable binding.
<!DOCTYPE html>
<head>
<title>KnockoutJS Disable Binding</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
function ViewModel (){
hasFeedback = ko.observable('');
};
Output
Let's carry out the following steps to see how the above code works:
99
KnockoutJS
You can also use a random expression to decide whether the element should be disabled
or not.
Value Binding
This binding is used to link respective DOM element's value into ViewModel property.
Mostly, this is used with elements such as input, select, and textarea. This is similar
to text binding, the difference being, in value binding data can be changed by the user
and the ViewModel will update it automatically.
Syntax
value: <binding-value>
Parameters
HTML DOM element's value property is set to parameter value. Earlier values will
be overwritten.
If the parameter is an observable value, then the elements value is updated as and
when the underlying observable is changed. Element is processed only once if
no observable is used.
valueUpdate is an extra parameter which can also be supplied for extra features.
KO uses additional events to detect extra changes when valueUpdate parameter is
used in binding. Following are some common events:
100
KnockoutJS
Example
Let us look at the following example which demonstrates the use of value binding.
<!DOCTYPE html>
<head>
<title>KnockoutJS Value Binding</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
function ViewModel (){
this.yourName = ko.observable('');
};
Output
Let's carry out the following steps to see how the above code works:
101
KnockoutJS
Observations
Example
Let us take a look at the following example in which valueAllowUnset option is used.
<!DOCTYPE html>
<head>
<title>KnockoutJS Value Binding - working with drop-down lists</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type="text/javascript"></script>
</head>
<body>
<p>Select a City:
102
KnockoutJS
<script type="text/javascript">
function ViewModel (){
this.cities = ko.observableArray(['Washington D.C.', 'Boston',
'Baltimore']);
selectedCity = ko.observable('Newark')
};
var vm = new ViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works:
selectedCity is assigned with value which is not present in the list. This makes the
drop-down blank for the first time.
103
KnockoutJS
If you refer a simple property on ViewModel, KO will set the form element's initial
state to property value. If the form element is changed, then KO will write back the
new values to property but it cannot detect any changes in the property, thus
making it a one-way binding.
If you refer something which is not simple, such as the result of comparison or a
function call then, KO will set the form element's initial state to that value but
cannot write any more changes made to the form element by the user. We can call
this as one-time value setter.
Example
Following code snippet shows the use of observable and non-observable properties.
<!-- One-way binding. Populates textbox; syncs only from textbox to model. -->
<p>Second value: <input data-bind="value: secondVal" /></p>
<!-- No binding. Populates textbox, but doesn't react to any changes. -->
<p>Third value: <input data-bind="value: secondVal.length > 8" /></p>
<script type="text/javascript">
function viewModel() {
firstVal = ko.observable("hi there"), // Observable
secondVal = "Wats up!!!" // Not observable
};
</script>
104
KnockoutJS
textInput Binding
This binding is used to create two-way binding between text box or textarea and
ViewModel property. The difference between this and value binding is that this binding
makes immediate updates available from HTML DOM for various input types.
Syntax
textInput: <binding-value>
Parameters
HTML DOM element's value property is set to parameter value. Earlier values will
be overwritten.
If the parameter is an observable, then the elements value is updated as and when
the underlying observable is changed. Element is processed only once, if
no observable is used.
In most of the situations textInput is preferred over value binding due to the
capacity of textInput to provide live updates from DOM for every input type and
the ability to handle weird behavior of browsers.
Example
Let us take a look at the following example which demonstrates the use
of textInput binding.
<!DOCTYPE html>
<head>
<title>KnockoutJS textInput Binding </title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type="text/javascript"></script>
</head>
<body>
<p> Enter your reviews here: <br><br><textarea rows=5 data-bind="textInput:
someReview" ></textarea><br></p>
<p> You entered : <span data-bind="text: someReview"/></p>
<script type="text/javascript">
function ViewModel (){
this.someReview = ko.observable('');
105
KnockoutJS
};
var vm = new ViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works:
Observations
Immediate updates - By default, the value binding only updates the model when the
user moves the focus out of the textbox. The textInput binding updates the model
instantly after each keystroke or on other text entry mechanism.
Browser event weirdness handling - Browsers are highly unpredictable in the events
that fire in response to the unusual text entry mechanism such as dragging, cutting, or
allowing auto-complete suggestion. The value binding does not handle all text entry cases
on all browsers.
106
KnockoutJS
The textInput binding is especially designed to handle a wide range of weird behavior of
browsers. This way it provides consistent and instant model updates, even in case of
unusual text entry mechanisms.
hasFocus Binding
This binding is used to manually set the focus of a HTML DOM element through a ViewModel
property. This is also a two-way binding method. When the element is focused from UI,
Boolean value of ViewModel property is also changed and vice versa.
Syntax
hasFocus: <binding-value>
Parameters
If the parameter evaluates to true or true-like value (such as Integer or non-null
objects or non-empty string) then the DOM element is focused, else it is unfocused.
When the element is focused or unfocused by the user manually, the Boolean
ViewModel property is also changed accordingly.
Example
Let us take a look at the following example which demonstrates the use
of hasFocus binding.
<!DOCTYPE html>
<head>
<title>KnockoutJS hasFocus Binding</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type="text/javascript"></script>
</head>
<body>
107
KnockoutJS
<script type="text/javascript">
function ViewModel (){
this.primaryContact = ko.observable();
this.contactFlag = ko.observable(false);
this.setFocusFlag = function(){
this.contactFlag(true);
}
};
Output
Let's carry out the following steps to see how the above code works:
108
KnockoutJS
checked Binding
This binding is used to create a link between a checkable form element and ViewModel
property. Mostly these form elements are inclusive of check box and radio buttons. This is
also a two-way binding method wherein the moment the user checks form control, the
respective ViewModel property is changed and vice versa.
Syntax
checked: <binding-value>
Parameters
Main Parameters
The checkable element's state is set to parameter value. Earlier the value will be
overwritten.
Checkbox - The DOM element is checked when the ViewModel parameter value
is true and is unchecked if it is false. Non-zero numbers, non-empty string, and
non-null objects are interpreted at true Boolean value, whereas undefined, zero,
and empty strings are considered as false value.
Additional Parameters
checkedValue - checkedValue option is used to hold the value used by
the checkedbinding instead of the element's value attribute. This is very useful
when the checked value is something other than a String (like an Integer or an
object).
For example, take a look at the following code snippet where the item object themselves
are included into chosenValue array, when the respective checkboxes are checked.
109
KnockoutJS
<script type="text/javascript">
var viewModel = {
itemsToBeSeen: ko.observableArray([
{ itemName: 'Item Number One' },
{ itemName: 'Item Number Two' }
]),
chosenValue: ko.observableArray()
};
</script>
If the checkedValue parameter is an Observable value, then the binding will update the
checked model property whenever the underlying value changes. For radio buttons, KO
will just update the model value. For checkboxes, it will replace the old value with the new
value.
Example
Let us take a look at the following example which demonstrates the use of checkbox
control.
<!DOCTYPE html>
<head>
<title>KnockoutJS Checked checkbox Binding</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type="text/javascript"></script>
</head>
<body>
<p> The required files are installed. Please check below to complete
installation </p>
<p><input type="checkbox" data-bind="checked: agreeFlag" />I agree to all
terms and conditions applied.</p>
<button data-bind="enable: agreeFlag">Finish</button>
<script type="text/javascript">
function ViewModel () {
this.agreeFlag= ko.observable(false) // Initially unchecked
};
110
KnockoutJS
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works:
Example
Let us take a look at the following example which demonstrates the use of radio-button
control.
<!DOCTYPE html>
<head>
<title>KnockoutJS Checked Radio Button Binding</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type="text/javascript"></script>
</head>
<body>
<p> Select gender type from below:</p>
<div><input type="radio" name="gender" value="Male" data-bind="checked:
checkGender" /> Male</div>
<div><input type="radio" name="gender" value="Female" data-bind="checked:
checkGender" /> Female</div>
111
KnockoutJS
<script type="text/javascript">
function ViewModel () {
checkGender= ko.observable("Male") // Initially male is selected
};
Output
Let's carry out the following steps to see how the above code works:
112
KnockoutJS
options Binding
This binding is used to define the options for a select element. This can be used for either
drop-down list or a multi-select list. This binding cannot be used with anything other than
<select> elements.
Syntax
options: <binding-array>
Parameters
Parameter to be passed here is an array. For each entry in array, the option will be
added for respective select node. Earlier option will be removed.
If the parameter is an observable value, then the element's available options will
be updated as and when the underlying observable is changed. Element is
processed only once, if no observable is used.
Additional Parameters
o optionsText - This parameter allows you to specify which object property you
want to set as text in the dropdown list. This parameter can also include a
function, which returns the property to be used.
o optionsAfterRender - Use this for running some custom logic on the existing
option elements.
o selectedOptions - This is used to read and write the selected options from a
multi select list.
113
KnockoutJS
Example
Let us take a look at the following example which demonstrates the use of options binding.
<!DOCTYPE html>
<head>
<title>KnockoutJS Options Binding</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type="text/javascript"></script>
</head>
<body>
<p>Tutorials Library:
<select data-bind="
options: availableTutorials,
value: selectedTutorial,
optionsCaption: 'Choose tutuorial...',
"></select></p>
<p>You have selected <b><span data-bind="text:selectedTutorial"></b></span>
<script type="text/javascript">
function ViewModel (){
this.selectedTutorial = ko.observable();
this.availableTutorials = ko.observableArray(['Academic','Big
Data','Databases','Java Technologies','Mainframe',
'Management','Microsoft Technologies','Mobile
Development','Programming','Software Quality']);
};
var vm = new ViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
114
KnockoutJS
Output
Let's carry out the following steps to see how the above code works:
Observations
The data item against which it is bound; this will be undefined for the caption
element.
115
KnockoutJS
Example
Let us take a look at the following example which uses optionsAfterRender to add a disable
binding to each option.
<!DOCTYPE html>
<head>
<title>KnockoutJS Options Binding - using optionsAfterRender </title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
function ViewModel() {
myItems = [
{ name: 'First Class', id: 1, disable: ko.observable(false)},
{ name: 'Executive Class', id: 2, disable: ko.observable(true)},
{ name: 'Second Class', id: 3, disable: ko.observable(false)}
];
setOptionDisable = function(option, item) {
ko.applyBindingsToNode(option, {disable: item.disable}, item);
}
};
var vm = new ViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
116
KnockoutJS
Output
Let's carry out the following steps to see how the above code works:
selectedOptions Binding
This binding is used to work with elements which are selected currently in the multi list
select form control. This binding can be used with option binding and <select> form control
only.
When the user selects or de-selects an item in the multi-select list, this adds or removes
the corresponding value to an array on the view model. If it is an Observable array then
then the items selected or de-selected from the UI are also updated in the array in
ViewModel, making it a two-way binding method.
Syntax
selectedOptions: <binding-array>
Parameters
Parameter here will be an array (can also be an Observable). The active items from
select element are stored into this array. Earlier items will be overwritten.
If the parameter is Observable array, then the items selected are updated as and
when the underlying observable is changed. Element is processed only once, if no
Observable array is used.
117
KnockoutJS
Example
Let us take a look at the following example which demonstrates the use of selectedOptions
Binding.
<!DOCTYPE html>
<head>
<title>KnockoutJS selectedOptions Binding</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type="text/javascript"></script>
</head>
<body>
<p>Tutorials Library:<br><br>
<select size= 10 multiple='true' data-bind="
options: availableTutorials,
selectedOptions: selectedTutorials
"></select></p>
<p>(Press control and select for multiple options.)</p>
<p>You have chosen below Tutorials:</p>
<p><ul data-bind="foreach: selectedTutorials">
<li>
<span data-bind="text: $data"> </span>
</li>
</ul></p>
<script type="text/javascript">
function ViewModel() {
self = this;
self.availableTutorials = ko.observableArray(['Academic','Big
Data','Databases','Java Technologies','Mainframe',
'Management','Microsoft Technologies','Mobile
Development','Programming','Software Quality']);
self.selectedTutorials = ko.observableArray();
};
var vm = new ViewModel();
ko.applyBindings(vm);
118
KnockoutJS
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works:
uniqueName Binding
This binding is used to generate a unique name for a DOM element. If the DOM element
did not have a name attribute, this binding gives it one and sets it to some unique string
value.
You won’t need to use this often. It’s only useful in a few rare cases, for example:
jQuery Validation currently will only validate elements that have names. To use this
with a Knockout UI, it’s sometimes necessary to apply the uniqueName binding to
avoid confusing jQuery Validation.
IE 6 does not allow radio buttons to be checked if they don’t have a name attribute.
KO will internally use uniqueName on those elements to ensure they can be
checked.
119
KnockoutJS
Syntax
uniqueName: <binding-value>
Parameters
Parameter here will be Boolean value true or false or an expression resulting in Boolean
like value. A unique name is generated by KO for the element for which this parameter is
set to true or true-like value.
Example
Let us take a look at the following example which demonstrates the use
of uniqueName binding.
<!DOCTYPE html>
<head>
<title>KnockoutJS UniqueName Binding</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
function ViewModel (){
this.someValue = ko.observable();
this.showMessage = function(){
alert(" Nice Name"+ "\nSee rendered markup to view unique name generated!!!");
}
};
120
KnockoutJS
Output
Let's carry out the following steps to see how the above code works:
121
8. KnockoutJS ─ Dependency TrackingKnockoutJS
KnockoutJs automatically tracks the dependencies when the values get updated. It has a
single object called dependency tracker (ko.dependencyDetection) which acts as an
intermediate between the two parties for subscribing the dependencies.
Example
<!DOCTYPE html>
<html>
<head>
<title>KnockoutJS How Dependency Tracking Works</title>
<!-- CDN's-->
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-
3.1.0.js" type="text/javascript"></script>
</head>
<body>
<div>
<form data-bind="submit: addFruits">
<b>Add Fruits:</b>
122
KnockoutJS
Output
Let's carry out the following steps to see how the above code works:
123
KnockoutJS
Example
<!DOCTYPE html>
<html>
<head>
<title>KnockoutJs Controlling Dependencies Using Peek</title>
<!-- CDN's-->
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type="text/javascript"></script>
</head>
<body>
<div class="logblock">
<h3>Computed Log</h3>
<pre class="log" data-bind="html: computedLog"></pre>
</div>
<script>
function AppData() {
this.firstName = ko.observable('John');
this.lastName = ko.observable('Burns');
this.computedLog = ko.observable('Log: ');
this.fullName = ko.computed(function () {
124
KnockoutJS
this.step = ko.observable(0);
this.next = function () {
this.step(this.step() === 2 ? 0 : this.step()+1);
};
};
ko.applyBindings(new AppData());
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works:
125
KnockoutJS
Observations
126
9. KnockoutJS ─ Templating KnockoutJS
Template is a set of DOM elements which can be used repetitively. Templating makes it
easy to build complex applications due to its property of minimizing duplication of DOM
elements.
Native templating: This method supports the control flow bindings such as foreach,
with, and if. These bindings capture HTML markup existing in the element and use it as
template for random items. No external library is required for this templating.
Syntax
template: <parameter-value>
Note that type is provided as text/html in the script block to notify KO that, it is not an
executable block rather just a template block which needs to be rendered.
Parameters
Combination of the following properties can be sent as parameter-value to template.
nodes - This represents an array of DOM nodes to be used as the template. This
parameter is ignored if the name parameter is passed.
if - Template will be served if the given condition results in true or true-like value.
127
KnockoutJS
Observations
Example
<!DOCTYPE html>
<head>
<title>KnockoutJS Templating - Named Template</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type="text/javascript"></script>
</head>
<body>
<h2>Friends List</h2>
Here are the Friends from your contact page:
<div data-bind="template: { name: 'friend-template', data: friend1 }"></div>
<div data-bind="template: { name: 'friend-template', data: friend2 }"></div>
<script type="text/javascript">
function MyViewModel() {
this.friend1= { name: 'Smith', contactNumber: 4556750345, email:
'smith123@gmail.com' };
this.friend2 = { name: 'Jack', contactNumber: 6789358001, email:
'jack123@yahoo.com' };
}
128
KnockoutJS
</script>
</body>
</html>
Output
Let's carry out the following steps to see how the above code works:
Example
<!DOCTYPE html>
<head>
<title>KnockoutJS Templating - foreach used with Template</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type="text/javascript"></script>
</head>
129
KnockoutJS
<body>
<h2>Friends List</h2>
Here are the Friends from your contact page:
<div data-bind="template: { name: 'friend-template', foreach:
friends }"></div>
<script type="text/javascript">
function MyViewModel() {
this.friends = [
{name: 'Smith', contactNumber: 4556750345, email:
'smith123@gmail.com' },
{ name: 'Jack', contactNumber: 6789358001, email:
'jack123@yahoo.com' },
{ name: 'Lisa', contactNumber: 4567893131, email:
'lisa343@yahoo.com' }
]
}
Output
Let's carry out the following steps to see how the above code works:
130
KnockoutJS
It becomes easy to refer to parent objects from inside of foreach loops by creating alias.
This feature is useful when the code is complex and nested at multiple levels.
Example
<!DOCTYPE html>
<head>
<title>KnockoutJS Templating - using alias in Template</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type="text/javascript"></script>
</head>
<body>
131
KnockoutJS
<h2>Friends List</h2>
Here are the Friends from your contact page:
<ul data-bind="template: { name: 'friend-template', foreach: friends, as:
'frnz' }"></ul>
<script type="text/javascript">
function MyViewModel() {
this.friends = ko.observableArray( [
{name: 'Smith', contactNumber: [ 4556750345, 4356787934 ] ,
email: 'smith123@gmail.com' },
{ name: 'Jack', contactNumber: [ 6789358001, 3456895445 ],
email: 'jack123@yahoo.com' },
{ name: 'Lisa', contactNumber: [ 4567893131, 9876456783,
1349873445 ], email: 'lisa343@yahoo.com' }
]);
}
var vm = new MyViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
132
KnockoutJS
Output
Let's carry out the following steps to see how the above code works:
Friends List
Contact Numbers
4556750345
4356787934
Email-id: smith123@gmail.com
Jack
Contact Numbers
6789358001
3456895445
Email-id: jack123@yahoo.com
Lisa
Contact Numbers
4567893131
9876456783
1349873445
Email-id: lisa343@yahoo.com
afterAdd - This function is invoked when a new item is added to the array mentioned in
foreach.
beforeRemove - This function is invoked just before removing the item from an array
mentioned in foreach.
133
KnockoutJS
afterRender - Function mentioned here is invoked every time foreach is rendered and
new entries are added to the array.
Example
<!DOCTYPE html>
<head>
<title>KnockoutJS Templating - Use of afterRender Template</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type="text/javascript"></script>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"
type="text/javascript"></script>
</head>
<body>
<h2>Friends List</h2>
Here are the Friends from your contact page:
<div data-bind="template: { name: 'friend-template', foreach: friends ,
afterRender: afterProcess}"></div>
<script type="text/javascript">
function MyViewModel() {
self= this;
this.friends = ko.observableArray([
{name: 'Smith', contactNumber: 4556750345, email:
'smith123@gmail.com' },
{ name: 'Jack', contactNumber: 6789358001, email:
'jack123@yahoo.com' },
])
134
KnockoutJS
Output
Let's carry out the following steps to see how the above code works:
135
KnockoutJS
Example
<!DOCTYPE html>
<head>
<title>KnockoutJS Templating - Dynamic Template</title>
<script src="https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type="text/javascript"></script>
</head>
<body>
<h2>Friends List</h2>
Here are the Friends from your contact page:
<div data-bind="template: { name: whichTemplate, foreach: friends }"></div>
<script type="text/javascript">
function MyViewModel() {
this.friends = ko.observableArray([
{name: 'Smith', contactNumber: 4556750345, email:
'smith123@gmail.com' ,active: ko.observable(true) },
{name: 'Jack', contactNumber: 6789358001, email:
'jack123@yahoo.com', active: ko.observable(false) },
]);
this.whichTemplate = function(friends){
136
KnockoutJS
Output
Let's carry out the following steps to see how the above code works:
As mentioned on the official site JQuery.tmpl is no longer under active development since
December 2011. Hence, KO's native templating is only recommended instead of
JQuery.tmpl or any other string-based template engine.
137
10. KnockoutJS ─ Components KnockoutJS
Components are a huge way of organizing the UI code for structuring a large application
and promoting code reusability.
It is inherited or nested from other component. For loading and configuration, it defines
its own conventions or logic.
It is packaged to reuse throughout the application or the project. Represents the complete
sections of application or small controls/widgets. It can be loaded or preloaded on demand.
Component Registration
Components can register using the ko.components.register() API. It helps to load and
represent the components in KO. Component name with configuration is expected for
registration. The configuration specifies how to determine the viewModel and template.
Syntax
Components can be registered as follows:
ko.components.register('component-name', {
viewModel: {...}, //function code
template: {....) //function code
});
viewModel is optional, and can take any of the viewModel formats listed in the
next sections.
template is required, and can take any of the template formats listed in the next
sections.
138
KnockoutJS
Stating a ViewModel
Following table lists the viewModel formats that can be used to register the components.
constructor function
It creates a separate viewModel object for each component. The object or
function is used to bind in components view.
function SomeComponentViewModel(params) {
1 this.someProperty = params.something;
}
ko.components.register('component name', {
viewModel: SomeComponentViewModel,
template: ...
});
ko.components.register('component name', {
viewModel: { instance: sharedViewModelInstance },
template: ...
});
139
KnockoutJS
createViewModel
It calls a function which acts as a factory and can be used as view model that
can return an object.
ko.components.register('component name', {
viewModel: {
...}
},
template: ....
});
AMD module
ko.components.register('component name', {
viewModel: { require: 'some/module/name' },
template: ...
});
4
define(['knockout'], function(ko) {
function MyViewModel() {
// ...
}
return MyViewModel;
});
140
KnockoutJS
Stating a Template
Following table lists the template formats that can be used to register the components.
element ID
ko.components.register('component name', {
1 template: { element: 'component-template' },
viewModel: ...
});
element instance
2
ko.components.register('component name', {
template: { element: elemInstance },
viewModel: ...
});
string of markup
ko.components.register('component name', {
3 template: '<input data-bind="value: yourName" />\
<button data-bind="click: addEmp">Add Emp </button>',
viewModel: ...
});
141
KnockoutJS
DOM nodes
var emp = [
document.getElementById('node 1'),
document.getElementById('node 2'),
4 ];
ko.components.register('component name', {
template: emp,
viewModel: ...
});
document fragement
ko.components.register('component name', {
5
template: someDocumentFragmentInstance,
viewModel: ...
});
AMD module
ko.components.register('component name', {
6
template: { require: 'some/template' },
viewModel: ...
});
142
KnockoutJS
Component Binding
There are two ways of component binding.
Full syntax: It passes the parameter and object to the component. It can pass
using the following properties:
<div data-bind='component: {
name: "tutorials point",
params: { mode: "detailed-list", items: productsList }
}'>
</div>
Shorthand syntax: It passes the string as a component name and it does not
include parameter in it.
ko.components.register('component name', {
template:'<input data-bind="value: someName" />,
});
<!--ko.component: ""-->
<!--/ko-->
Custom Element
Custom element is a way for rendering a component. Here, you can directly write a self-
descriptive markup element name instead of defining a placeholder, where the
components are binded through it.
143
KnockoutJS
Passing Parameter
params attribute is used to pass the parameter to component viewModel. It is similar to
data-bind attribute. The contents of the params attribute are interpreted like a JavaScript
object literal (just like a data-bind attribute), so you can pass arbitrary values of any type.
It can pass the parameter in following ways:
<some-component
params='simpleExpression: 1 + 1,
simpleObservable: myObservable,
observableExpression: myObservable() + 1'>
</some-component>
<some-component
params='objectValue:{a: 3, b: 2},
dateValue: new date(),
stringValue: "Hi",
numericValue:123,
boolValue: true/false,
ModelProperty: ModelValue'>
</some-component>
144
KnockoutJS
ko.components.getComponentNameForNode = function(node) {
...
... //function code
...
}
Example
<!DOCTYPE html>
<head>
<title>KnockoutJS Components</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></scrip
t>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-
min.js"></script>
</head>
<body>
<!--params attribute is used to pass the parameter to component viewModel.-->
<click params="a: a, b: b"></click>
145
KnockoutJS
this.callback = function(num){
self.b(parseInt(num));
self.a( self.a() + parseInt(num) );
};
},
template: { element: 'click-l' }
});
ko.applyBindings(new viewModel() );
</script>
</body>
</html>
146
KnockoutJS
Output
Let's carry out the following steps to see how the above code works:
Component Loaders
Component loaders are used to pass the template/viewModel pair asynchronously for the
given component name.
ko.components.defaultLoader
ko.components.register(name, configuration)
1
Component is registered.
147
KnockoutJS
ko.components.isRegistered(name)
2 If the particular component name is already registered, then it returns
as true else false.
ko.components.unregister(name)
3
The component name is removed from the registry.
ko.components.get(name, callback)
This function goes turn by turn to each registered loader to find who has
4 passed the viewModel/template definition for component name as first.
Then it returns viewModel/template declaration by invoking callback. If
the registered loader could not find anything about the component, then
it invokes callback(null).
ko.components.clearCachedDefinition(name)
5 This function can be called when we want to clear the given component
cache entry. If the component is needed next time, again the loaders will
be consulted.
148