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.

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 comment

Create a website or blog at WordPress.com