Why we Need Observable Properties in Knockout.js

Prior to reading thsi article I recommend you read:

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



Let us try to understand the Knockout feature of Automatic UI Refresh with an example.

Let us create a simple ViewModel as in the following:

var viewModel =
{
   message: "Hello World",
};

Now create a simple View. In the View we are binding the value and text to the input and span elements respectively.

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


Now on running the application, you will see that when the value in the input TextBox is changed the value is not being refreshed automatically on the view.

Observable Properties

To do an automatic UI refresh, you need to create ViewModel properties as observable properties. You can create that as in the following:

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


Essentially you need to convert the normal properties of ViewModel as observable properties to do an automatic UI refresh.

Observable Properties in Knockout

Now when the application is run you will find that the UI is being refrehsed autometically. You will notice that when you change the value in the input TextBox the value is being refreshed automatically in the view.

Knockout Observable

Now these are the main tasks performed by observable properties:

  • Notifification of changes to subscribers
  • Automatically detect dependencies
  • Update the view automatically

Reading ViewModel properties

You can read a ViewModel property as in the following:

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


Writing ViewModel properties

You can modify a ViewModel property as in the following:

viewModel.message("whatsup")

Writing multiple observable properties

KO allows you to write multiple observable properties with a chained syntax. Let us say we have a ViewModel as in the following:

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 in the following:

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 do:

  1. Two way binding
  2. Notify the subscribers
  3. Automatic refresh UI

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

Up Next
    Ebook Download
    View all
    Learn
    View all