Working with Knockout.js Part 3: Working with Observables

Read here working with Knockout.js Part 2: Understanding MVVM

Read here Getting started with Knockout.js

So far we have learnt basics of Knockout.js. In last two posts we tried to understand need of KO and MVVM pattern.

One of the most essential and important feature of MVVM is, “When View Model changes View must be notified such that UI will be refreshed automatically

image

In Part 2 we created ViewModel as following. This is a simple ViewModel and would not notify View on changes of the property’s value.


var studentViewModel = {

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

}

To enable automatic notification from ViewModel to View, we need to make properties of ViewModel as an OBSERVABLE PROPERTIES

We can make a property Observable as following

image

So we can rewrite StuentViewModel with automatic notification as following


var studentViewModel = {

studentName: ko.observable('DJ'),
studentGrade: ko.observable('B'),
studentMarks: ko.observable(90)

}

Now whenever value of property changes in the ViewModel View will be notified and UI will be refreshed automatically.

There is no need to change anything at View side. Different View Elements are now subscribed to ViewModel properties. Now whenever value at ViewModel will be changed , View will be notified.


<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 can read and write from observable using JavaScript getter and setter. A observable value can be read as following

image

We can write to observable as following

image

So now you see how much easier it is in KO to autmetically refresh UI on the chnages in ViewModel. Only we need to make ViewModel property as observable. I hop you find this post useful. In next post we will learn about Compound Observables. Thanks for reading.

7 responses to “Working with Knockout.js Part 3: Working with Observables”

  1. […] Working with Knockout.js Part 3: Working with Observables (Dhananjay Kumar) […]

  2. […] Working with Knockout.js Part 3: Working with Observables (debug mode……) […]

  3. Nice Post DJ,could you provide us the sample app for Knockout.js

  4. […] Working with Knockout.js Part 3: Working with Observables […]

  5. I hope KO will make observables work without using functions (like in AngularJS).

  6. […] Working with Knockout.js Part 3: Working with Observables […]

Leave a comment

Create a website or blog at WordPress.com