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'),


 <span data-bind="text:studentName"></span>

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,


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";
 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,

 <span data-bind="text:grade"></span>

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.

3 responses to “Working with Knockout.js Part 6: Working with text binding”

  1. […] Working with Knockout.js Part 6: Working with text binding (Dhananjay Kumar) […]

  2. […] Working with Knockout.js Part 6: Working with text binding (debug mode……) […]

  3. […] Working with Knockout.js Part 6: Working with text binding (Dhananjay Kumar) […]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s