Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon

Data bindings with Knockout.js

Save for later
  • 7 min read
  • 23 Apr 2018

article-image
Today, we will learn about three data binding abilities of Knockout.js. Data bindings are attributes added by the framework for the purpose of data access between elements and view scope. While Observable arrays are efficient in accessing the list of objects with the number of operations on top of the display of the list using the foreach function, Knockout.js has provided three additional data binding abilities:
  • Control-flow bindings
  • Appearance bindings
  • Interactive bindings


Let us review these data bindings in detail in the following sections.

Control-flow bindings


As the name suggests, control-flow bindings help us access the data elements based on a certain condition. The if, if-not, and with are the control-flow bindings available from the Knockout.js.

In the following example, we will be using if and with control-flow bindings. We have

added a new attribute to the Employee object called age; we are displaying the age value in green only if it is greater than 20. Similarly, we have added another markedEmployee. With control-flow binding, we can limit the scope of access to that specific employee object in the following paragraph. Add the following code snippet to index.html and run the program to see the if and with control-flow bindings working:

<!DOCTYPE html>
<html>
<head>
<title>Knockout JS</title>
</head>
<body>
<h1>Welcome to Knockout JS programming</h1>
<table border="1" >
<tr >
<th colspan="2" style="padding:10px;">
<b>Employee Data - Organization :
<span style="color:red" data-bind='text: organizationName'>
</span>
</b>
</th>
</tr>
<tr>
<td style="padding:10px;">Employee First Name:</td>
<td style="padding:10px;">
<span data-bind='text: empFirstName'></span>
</td>
</tr>
<tr>
<td style="padding:10px;">Employee Last Name:</td>
<td style="padding:10px;">
<span data-bind='text: empLastName'></span>
</td>
</tr>
</table>
<p>Organization Full Name :
<span style="color:red" data-bind='text: orgFullName'></span>
</p>
<!-- Observable Arrays-->
<h2>Observable Array Example : </h2>
<table border="1">
<thead><tr>
<th style="padding:10px;">First Name</th>
<th style="padding:10px;">Last Name</th>
<th style="padding:10px;">Age</th>
</tr></thead>
<tbody data-bind='foreach: organization'>
<tr>
<td style="padding:10px;" data-bind='text: firstName'></td>
<td style="padding:10px;" data-bind='text: lastName'></td>
<td data-bind="if: age() > 20"
style="color: green;padding:10px;">
<span data-bind='text:age'></span>
</td>
</tr>
</tbody>
</table>
<!-- with control flow bindings -->
<p data-bind='with: markedEmployee'>
Employee <strong data-bind="text: firstName() + ', ' + lastName()">
</strong> is marked with the age <strong data-bind='text: age'>
</strong>
</p>
<h2>Add New Employee to Observable Array</h2>
First Name : <input data-bind="value: newFirstName" />
Last Name : <input data-bind="value: newLastName" />
Age : <input data-bind="value: newEmpAge" />
<button data-bind='click: addEmployee'>Add Employee</button>
<!-- JavaScript resources -->
<script type='text/javascript' src='js/knockout-3.4.2.js'></script>
<script type='text/javascript'>
function Employee (firstName, lastName,age) {
this.firstName = ko.observable(firstName);
this.lastName = ko.observable(lastName);
this.age = ko.observable(age);
};
this.addEmployee = function() {
this.organization.push(new Employee
(employeeViewModel.newFirstName(),
employeeViewModel.newLastName(),
employeeViewModel.newEmpAge()));
};
var employeeViewModel = {
empFirstName: "Tony",
empLastName: "Henry",
//Observable
organizationName: ko.observable("Sun"),
newFirstName: ko.observable(""),
newLastName: ko.observable(""),
newEmpAge: ko.observable(""),
//With control flow object
markedEmployee: ko.observable(new Employee("Garry", "Parks",
"65")),
//Observable Arrays
organization : ko.observableArray([
new Employee("John", "Kennedy", "24"),
new Employee("Peter", "Hennes","18"),
new Employee("Richmond", "Smith","54")
])
};
//Computed Observable
employeeViewModel.orgFullName = ko.computed(function() {
return employeeViewModel.organizationName() + " Limited";
});
ko.applyBindings(employeeViewModel);
employeeViewModel.organizationName("Oracle");
</script>
</body>
</html>


Run the preceding program to see the if control-flow acting on the Age field, and the with control-flow showing a marked employee record with age 65:

data-bindings-with-knockout-js-img-0

Appearance bindings


Appearance bindings deal with displaying the data from binding elements on view components in formats such as text and HTML, and applying styles with the help of a set of six bindings, as follows:

  • Text: <value>—Sets the value to an element. Example:

<td data-bind='text: name'></td>

  • HTML: <value>—Sets the HTML value to an element. Example:

//JavaScript:

function Employee(firstname, lastname, age) {

...

this.formattedName = ko.computed(function() {

return "<strong>" + this.firstname() + "</strong>";

}, this);

}

//Html:

<span data-bind='html: markedEmployee().formattedName'></span>

  • Visible: <condition>—An element can be shown or hidden based on the condition. Example:

<td data-bind='visible: age() > 20' style='color: green'>

span data-bind='text:age'>

  • CSS: <object>—An element can be associated with a CSS class. Example:

//CSS:

.strongEmployee {

font-weight: bold;

}

//HTML:

<span data-bind='text: formattedName, css: {strongEmployee}'>

</span>

  • Style: <object>—Associates an inline style to the element. Example:

<span data-bind='text: age,

style: {color: age() > 20 ? "green" :"red"}'>

</span>

  • Attr: <object>—Defines an attribute for the element. Example:

<p><a data-bind='attr: {href: featuredEmployee().populatelink}'>

View Employee</a></p>

Interactive bindings


Interactive bindings help the user interact with the form elements to be associated with corresponding viewmodel methods or events to be triggered in the pages. Knockout JS supports the following interactive bindings:

  • Click: <method>—An element click invokes a ViewModel method. Example:

<button data-bind='click: addEmployee'>Submit</button>

  • Value:<property>—Associates the form element value to the ViewModel attribute. Example:
  • Unlock access to the largest independent learning library in Tech for FREE!
    Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
    Renews at €18.99/month. Cancel anytime

<td>Age: <input data-bind='value: age' /></td>

  • Event: <object>—With an user-initiated event, it invokes a method. Example:

<p data-bind='event: {mouseover: showEmployee,

mouseout: hideEmployee}'>

Age: <input data-bind='value: Age' /> </p>

  • Submit: <method>—With a form submit event, it can invoke a method. Example:

<form data-bind="submit: addEmployee">

<!—Employee form fields -->

<button type="submit">Submit</button>

</form>

  • Enable: <property>—Conditionally enables the form elements. Example: last name field is enabled only after adding first name field.

Disable: <property>—Conditionally disables the form elements. Example: last

name field is disabled after adding first name:

<p>Last Name:

<input data-bind='value: lastName, disable: firstName' />

</p>

  • Checked: <property>—Associates a checkbox or radio element to the ViewModel attribute. Example:

<p>Gender: <input data-bind='checked:gender' type='checkbox' /></p>

  • Options: <array>—Defines a ViewModel array for the<select> element. Example:

//Javascript:

this.designations = ko.observableArray(['manager',

'administrator']);

//Html:

Designation: <select data-bind='options: designations'></select>

  • selectedOptions: <array>—Defines the active/selected element from the <select>
    element. Example:

Designation: <select data-bind='options: designations,

optionsText:"Select",

selectedOptions:defaultDesignation'>

</select>

  • hasfocus<property>—Associates the focus attribute to the element. Example:

First Name: <input data-bind='value: firstName,

hasfocus: firstNameHasFocus' />


We learned about data binding abilities of Knockout.js. You can know more about external data access and Hybrid Mobile Application Development from the book Oracle JET for Developers.

Read More

Text and appearance bindings and form field bindings

Getting to know KnockoutJS Templates