Observables in Knockout.js

Observables in Knockout.js provide a way for Knockout to know when parts of the View Model change. Observables therefore make it easy for the User Interface and the View Model to communicate.

In the Getting Started with Knockout.js post, the example given was showing how to create a basic view model and how to display one a couple of properties using data binding.

To rewrite the view model to use observables, you can change the view model code to look like the following:

var myViewModel = {
    personFirstName: ko.observable('John'),
    personLastName: ko.observable('Doe')
};
ko.applyBindings(myViewModel);

This will allow Knockout to be able to detect changes, and when it does, it will update the UI automatically.

To see the UI updating within the HTML document, add a couple of <input> fields allowing you to type in a first name and last name.

Enter first name <input type="text" data-bind="value: personFirstName">
The first name is <span data-bind="text: personFirstName"></span>
Enter last name <input type="text" data-bind="value: personLastName"> The last name is <span data-bind="text: personLastName"></span> <script type="text/javascript"> var myViewModel = { personFirstName: ko.observable('John'), personLastName: ko.observable('Doe') }; ko.applyBindings(myViewModel); </script>

You’ll notice that when the HTML document first loads, the <input> fields are populated with John and Doe based on the properties set in myViewModel.

Also note that the <input> fields use the ‘value’ binding. This means that when the user edits the values in the form control elements, it updates the values in your view model.

These values can then be seen within the <span> tags, which use the ‘text’ data binding.

Within Knockout.js, to read an observable, you can simply call it.

myViewModel.personFirstName(); // Returns 'John'

To write a new value to an observable, call it passing in your new value as an argument.

myViewModel.personFirstName('Jane');

You can also write to multiple observable properties using the chaining syntax.

myViewModel.personFirstName('Jane').personLastName('Dee');

Observable Arrays

Observable Arrays are used to detect and respond to changes of a collection of data.

To declare an ampty observable array, simply use the observableArray() syntax.

this.myArray = ko.observableArray();

The arrays can of course have existing data within them.

this.myArray = ko.observableArray(['John','Jane']);

You can read the length of an observable array and access the elements within.

alert('The length of the array is ' + this.myArray ().length);
alert('The first element is ' + this.myArray ()[0])