Control Flow bindings in Knockout.js

You can control flow of element on the view using Control Flow bindings of Knockout.js. There are four Control Flow bindings

  • foreach binding
  • if binding
  • ifnot binding
  • with binding

Out of these four bindings foreach and if bindings are used very often.

foreach binding

foreach binding repeat same markup for number of times equivalent to number of elements in an array. It also binds each repeat of mark-up to corresponding item of the array.

image

Let us try to understand it with an example. Assume we have a ViewModel which contains observable array as one of the observable.


var viewModel =
 {
 students: ko.observableArray
 ([
 {name :"Dan W", subject : "JavaScript" },
 { name: "Glenn B", subject: "Node" },
 { name: "Pinal D", subject: "SQL" }
 ])
 }

ViewModel contains a property students which is an observable array. We can bind this on view to a table or lists elements.


<table>
 <thead>
 <tr>
 <th>Name</th>
 <th>Subject</th>
 </tr>
 </thead>
 <tbody data-bind="foreach: students">
 <tr>
 <td data-bind="text: name"></td>
 <td data-bind="text: subject"></td>
 </tr>
 </tbody>
 </table>

As you notice that on the table body we are performing foreach binding. So mark-up inside table body would be repeated 3 times in this case. Since number of elements in observable array is 3.

On running this application you will get table rendered with three rows as below,

image

Next let us consider one complex scenario in which we want to add and remove students. So let us go ahead an update view model with computed observable to add and remove items from observable array


function viewModel()
 {
 var self=this;
 self.students= ko.observableArray
 ([
 {name :"Dan W", subject : "JavaScript" },
 { name: "Glenn B", subject: "Node" },
 { name: "Pinal D", subject: "SQL" }
 ]);
 self.addStudent= function ()
 {
 self.students.push({ name: "dj", subject: "JavaScript" });
 };
 self.removeStudent= function ()
 {
 self.students.remove(this);
 }
 }

ko.applyBindings(new viewModel());

There is nothing much fancy in above ViewModel. We just added computed observables to add and remove students. Next we can bind that to a view contains unordered list as below


<h4>Students</h4>
 <ul data-bind="foreach: students">
 <li>Name at position <span data-bind="text: $index"></span>:
 <span data-bind="text: name"></span>
 <a href="#" data-bind="click: $parent.removeStudent">Remove</a>
 </li>
 </ul>
 <button data-bind="click: addStudent">Add</button>

On running application you will find that now you can add and remove student

image

You can use $index, $parent, $data with foreach binding as well. For example

  • You can read index of a particular element using $index.
  • You can read array element using $data. Not a particular element
  • You can read parent viewmodel or other properties of viewmodel using $parent

if binding

if binding allows whether a section of mark-up will appear or not. Unlikely visible binding if binding add or remove markup from the DOM. It performs following tasks,

  • Add or remove markup from the DOM
  • Make sure that data-bind attribute is having applied on the markup

Now let us take if binding in action. Let us say you have ViewModel as below


var viewModel =
 {
 show : ko.observable(false)
 }

ko.applyBindings(viewModel);

On View we can do binding as follows


<label><input type="checkbox" data-bind="checked: show" />Display Div</label>
<div data-bind="if: show">Visible/Hide using if binding </div>

As you notice that we are doing checked binding on input checkbox whereas performing if binding on div. If value of ViewModel property evaluates to non-false value then then div would be visible. Input is toggling value of show property.

Let us take another example in which we will learn that how if binding is useful in case of working with null. As you know if binding add or removes elements on the DOM having their data binding applied on that. Consider following ViewModel


function viewModel() {
 var self = this;
 self.students = ko.observableArray
 ([
 { name: "Dan W", subject: null },
 { name: "Glenn B", subject: { music: 'guitar' } },
 { name: "Pinal D", subject: { music: 'drum' } }
 ]);

};

Next we need to do if binding on the view,


<h4>Students</h4>
 <ul data-bind="foreach: students">
 <li>
 Student: <b data-bind="text: name"> </b>
 <div data-bind="if: subject">
 Subject: <b data-bind="text: subject.music"> </b>
 </div>
 </li>
</ul>

Above you see that we are applying if binding on div going to display subject. If binding add or remove on basis of non-falsie value. So for student subject value is set to null this div will not get created. If you try to achieve it using visible binding then for any student for which value if subject is set to null you will get subject.music throwing exception.

Ifnot binding

This is exactly the same as if binding. it only inverts the value passed to it.

So let us say you have ViewModel as below,


var viewModel =
 {
 display : ko.observable(false)
 }

and you bind this to a view as given below,


<div data-bind="ifnot: display">
 <h1>hello</h1>
 </div>

On running you will find div is added on the DOM even though display property in ViewModel is set to false. Because ifnot binding invert value of property in ViewModel.

When you create MVVM application using Knockout.js , control flow binding is very useful. You will use it very often and I hope you find this post useful in understanding control flow binding. Thanks for reading.

Why we need Observable Properties in Knockout.js

In this post we will take a look on why we need observable properties in Knockout.js

Before you read further this blog post, I would recommend you to read

Setting up Visual Studio for Knockoutjs Development

Create your First MVVM based JavaScript App in two simple steps using Knockoutjs

Inbuilt Bindings in Knockout.js: Controlling Text and Appearance

MVVM is, “When View Model changes View must be notified such that UI will be refreshed automatically

image

Let us try to understand Knockout feature Automatic UI Refresh with an example,

Let us create a simple ViewModel


var viewModel =
 {
 message: "Hello World",

 };

Now create a simple View. In View we are performing value and text binding on input and span element respectively.


<input type="text" data-bind="value:message" /> <br />
 <span data-bind="text:message" /> <br />

Now on running application, you will notice that when you change value in input textbox that value is not getting refreshed automatically on view.

image

To achieve automatic UI refresh, you need to create ViewModel properties as observable properties. You can create that as following,


var viewModel =
 {
 message: ko.observable("Hello World")

 };

Essentially you need to convert normal properties of ViewModel as observable properties to achieve automatic UI refresh.

image

Now on running application you will find that UI is getting refreshed automatically. You will notice that when you change value in input textbox that value is getting refreshed automatically on view.

clip_image001

Now these are the main tasks performed by observable properties

  • Notify about changes to subscribers
  • Automatically detect dependencies
  • To update view automatically

Reading ViewModel properties

You can read ViewModel property as below,


var m = viewModel.message();
 console.log(m);

Writing ViewModel properties

You can write ViewModel property as below,


viewModel.message("whatsup")

Writing multiple observable properties

KO allow you to write multiple observable property with chained syntax. Let us say we have a ViewModel as below,


var viewModel =
 {
 message: ko.observable("Hello World"),
 greet : ko.observable(23)
 };

And you want to update both properties. You can do that using chained syntax as below,

viewModel.message("whatsup").greet(45);
 var m = viewModel.message();
 var n = viewModel.greet();
 console.log(m);
 console.log(n);

So essentially we need observable properties in KO to achieve,

  • Two way binding
  • Notify the subscribers
  • Automatic refresh UI

I hope you find this post useful. Thanks for reading.

Working with Knockout.js Part 6: Working with text binding

Working with Knockout.js Part 5: Working with visible binding

Working with Knockout.js Part 4: Observable Arrays

Working with Knockout.js Part 3: Working with Observables

Working with Knockout.js part 2: Understanding MVVM

Working with Knockout.js Part 1: Getting started with Knockoutjs

In last post we started learning about bindings. We had a look on visible binding . In this post we will learn a very important text binding.

Text binding is used to set text property of view elements from the properties or values of ViewModel. You can bind text of a span as easily as depicted in following code snippet,


<script type="text/javascript">

<em id="__mceDel">
 var studentViewModel = {
 studentName: ko.observable('DJ'),

 }

 </script>
<body>
 <span data-bind="text:studentName"></span>
 <script>
 ko.applyBindings(studentViewModel);
 </script>
</body></em>

Above we are creating a ViewModel named studentViewModel with property studentName. In HTML we are binding text property of span. So we can bind text property using following syntax,

Capture

Some time you may come across requirement to dynamically set the value of text binding. That is very much possible using functions and expressions to determine value of the text. Let us assume we have a function in ViewModel as give below,


var studentViewModel = {
 marks: ko.observable(90),
 }

And we can create computed function as following. This function will determine grade of the student.

 studentViewModel.grade = ko.computed(function () {

 if (this.marks > 96)
 return "Grade A";
 else
 return "Grade B";

 }, studentViewModel);

And we can simply bind computed property as text binding to span element on view. You can do this as following,


<body>
 <span data-bind="text:grade"></span>
 <script>
 ko.applyBindings(studentViewModel);
 </script>
</body>

The other way we can dynamically set text binding value by using conditional statement while binding. We can do bind grade without computed function as following


<span data-bind="text:marks()> 10 ? 'Grade A':'Grade B'"></span>

In this way we can work with text binding in knockoutjs. In further posts we will discuss other bindings. I hope you find this post useful. Thanks for reading.

Working with Knockout.js part 2: Understanding MVVM

Read here Getting started with Knockout.js part1

In last post we had a discussion on Getting started with Knockout. In this post we will go one step further and understand different aspects of MVVM pattern and how Knockout.js helps us in creating web application adhering to MVVM pattern.

Let us start our discussion with understanding MVVM. MVVM stands for Model-View-ViewModel.

image

As you see that each component of MVVM has dedicated task to do. View never talks to Model directly. You can say that data is model, business logic is ViewModel and user interface is View. Let us summarize discussion of Model, ViewModel and View in bullet points

Model

  • Persisted data
  • Data being fetched from server
  • Data can be in HTML local storage
  • Data can be fetched from server using AJAX call or any other mechanism of calling service from JavaScript

ViewModel

  • It contains business logic
  • Temporary data to be displayed on the View
  • It handles all the user actions to send commands to ViewModel
  • It is a JavaScript object

View

  • This is User Interface of the application
  • This displays data from the ViewModel.
  • This sends command to ViewModel
  • User interaction occurs here
  • This is HTML with CSS

Now let us take our discussion into working with Knockout. We can create a ViewModel just like creating a JavaScript object. Below we are creating ViewModel for Student.


var studentViewModel = {

studentName: "DJ",
 studentGrade: "B",
 studentMarks : 90

}

After creating ViewModel to work with all browsers and earlier versions of HTML, we need to activate Knockout. That can be done as following in a script

image

You can put this script

  1. Either in bottom of HTML document
  2. In document ready of jquery

In VS2012 intellisense is supported for Knockout.js. You can see that applyBindings takes two parameters.

image

Two parameters of applyBindings are

  1. First parameter is ViewModel
  2. Second parameter is part of the document on which ViewModel will be bind

Second parameter is very essential. Suppose a scenario in which you have multiple ViewModel and you want to associate them with different elements of HTML document. In that case you will have to create different Knockout bindings associating different ViewModel with different elements from View. Below we are applying studentViewModel to studentdiv from the View.

image

We can create View with Declarative Binding as following. Using data-bind attribute we can bind data from ViewModel to elements of View. You can see that in this case we are putting script to apply Knockout binding at the bottom of HTML document.


<body>
 <span data-bind="text:studentName"></span>
 <span data-bind="text:studentGrade"></span>
 <span data-bind="text:studentMarks"></span>
 <script>
 ko.applyBindings(studentViewModel);
 </script>
</body>

We saw in this post that how Knockout helps so easily to create an application adhering to MVVM pattern. We also learnt about different component of MVVM pattern. We learnt about creating ViewModel and View. We also learnt bindings in Knockout.js. In further posts we will discuss more complex aspects of Knockout.js. I hope you find this post useful. Thanks for reading.

Working with Knockout.js Part 1: Getting started with Knockoutjs

In this post we will take a look on Knockout.js. We will start with basic theoretical introduction and then to some basic demo on Knockout.js

image

Knockout.js helps us to create dynamic JavaScript UI using the MVVM pattern. It simplifies the task of linking Data Model to the dynamic JavaScript UI.

Knockout.js is a JavaScript library and it helps us to create high responsive, very rich and interactive JavaScript UI adhering to MVVM pattern. It simplifies the task of binding data from Data Model to JavaScript UI. It is a pure JavaScript library and it works with almost all the browsers. It is an open source project under the license of MIT. It is very compact in size. Its zipped size is 13kb and it can be added over any existing web application.

Essentially Knockout.js helps to link a Data Model to UI. It tracks the changes and dynamically updates the UI. It helps to perform two ways binding in between UI and Data Model. It updates certain section of UI dynamically when data in data model is changed. It simplifies the task of binding and dynamic updating the UI.

Some of the features of Knockout.js can be outlined as below,

  • It detects the data changes in data model and updates respective part of the UI.
  • It binds data and UI declaratively. In other words declarative binding between data model and UI can be done using Knockout.js
  • It helps to create custom behavior. Custom behavior can be created as declarative binding.
  • Custom behavior created by Knockout.js can be reused with very less lines of code.
  • It helps to create complex dynamic UI using declarative bindings.
  • It helps to edit JSON data on the JavaScript UI.

Knockout.js is JavaScript MVVM framework and it helps in

image

Further in the post, we will explore each features of Knockout.js. You can download Knockout.js from here. You will get many versions of Knockout.js to download on the download page. For usual production purpose you can choose to download knockout-versionnumber.js file.

After downloading add reference of Knockout.js. Reference can be added as following,

image

Next let us create a ViewModel. We are going to create ViewModel for Product. A ViewModel can be created as following. You can see that in knockout ViewModel is nothing but a JavaScript array,

image

Once you have created ViewModel you need to apply binding. Binding can be applied as below,

image

Last step is to bind values from ViewModel on the view. That can be done as following. Using data-bind attribute values from ViewModel can be bind to element on View.

image

A complete example of Product ViewModel data being bind with elements of View is given below,


<!DOCTYPE html>
<html>
<head>
 <title></title>
 <script src="Scripts/jquery-1.7.1.js"></script>
 <script src="Scripts/knockout-2.2.0.js"></script>
 <script type="text/javascript" >
 $(document).ready(function () {

var ProductViewModel = {
 productname: "pen",
 productprice: 200,
 producttype :"education"
 };
 ko.applyBindings(ProductViewModel);

});

 </script>
</head>
<body>

<h2>Knockout Demo</h2>
 Product Name : <span id="namespan" data-bind="text:productname"></span> <br />
 Product Price : <span id ="pricespan" data-bind="text:productprice"></span><br />
 Product Type : <span id="typesapn" data-bind="text:producttype"></span> <br />

</body>
</html>

And as expected you will get values from ViewModel on View elements as following

image

This was small introduction of Knockout.js. In further posts we will get into more details of Knockout.js and see examples of its usage in real examples. I hope you find this post useful. Thanks for reading