Observable, Computed & ObservableArray in KnockoutJS

In this article, we will discuss about the three fundamental properties of KnockoutJS.

Introduction

In my previous KnockoutJS article, we discussed about the basics of KnockoutJS & MVVM design pattern. As the continuation of that, in this article, let us discuss the overview of the three main properties in KnockoutJS.

Three main properties of KnockoutJS

As I told, the three main properties of KnocoutJS are given below.

  1. Observable
  2. Computed/DependentObservable
  3. ObservableArray

Let us discuss about these properties.

Observable


Observable is the property that automatically will issue notifications whenever their value changes

Yes, Observable is a magic property of KnockoutJS which will notify the underlying viewmodal when there is change happens in the property.

Observable property can be created by ko.observable function which returns a function responsible for "observable" functionality.

 //Creating observable property. 
var name = ko.observable("");//Set the value for obervable
name("name");//Get the value from observable
alert(name());

Parameter for the ko.observable is the value for the property. If you want to set the property then call the observable property with the value. If you want to get the value from observable, then call the observable property without passing parameter.

For example, if you have a simple observable property bound with a textbox & a label which displays the value typed in that textbox.

If the value is entered into the textbox, once the focus of the textbox has lost, the value is updated into the observable property. As we have bound the name property with the label's text attribute, the value is displayed at the label.

Creating extenders for Observable:

Extender in KnockoutJS is nothing but adding a new feature to the existing observable property. Though KO is giving you the Read/Write options for the observable, we can add your own unique features to the observable.

You can create an extender by adding a new function to the ko.extenders's object. This functions accepts two parameter. The first parameter is the observable property on which we are extending & the second parameter is for options.

//Source: KnockoutJS.com 
ko.extenders.log = function(target, option) {
    target.subscribe(function(newValue) {
       console.log(option + ": " + newValue);
    });
    return target;
};


Manually subscribing for Observable:

If you want to subscribe for a observable, we can use the KO's subscribe function on the observable. By creating manual subscrition, you can do stuffs on the value change.

Callback function passed to the subscribe function will be executed when the observable value is changed. 


//Source: KnockoutJS.com 
vm.name.subscribe(function(newValue) {
    alert("The new name is " + newValue);
});


Computed

Computed property is observable (i.e., they notify on change) and they are computed based on the values of other observables.

A computed property value is calculated based on the other observables properties. Computed property can be created as like this.

 //Creating computed observable
message = ko.computed(function() { return "Hello" + this.name(); });
alert(message());

For example, we want to say Hello to the user who logged-in into your application, then we need to have the computed observable as like the above example.

In this example, the name observable property is tracked by the message computed property. Whenever the name property changes, then the value of the message property will be changes.

Writable computed observable property:

Basically computed observable property is readonly but KO provides the option to write into the computed observable property. To make the computed observable writable, KO has different way, we need to pass a object with read & write callbacks.

 this.result = ko.computed({
        read: function () {
            return this.firstNum() / this.secondNum();
        },
        write: function (value) {
            this.firstNum(value * this.secondNum());
        },
        owner: this
    });

In this above example, the write callback updates the firstNum from the input value.

ObservableArray

ObservableArray - not surprisingly, that's the observable equivalent of a regular array, which means it can automatically trigger UI updates whenever items are added or removed.

The observableArray property can be created using the ko.obervableArray function as like the below.

 //Creating observableArray
texts = ko.observableArray([]); //Adding item
texts.push({ simpleText: "Item" }); //Removing item
texts.remove(item);

ObservableArray makes the UI too responsive while adding/removing the elements to/from the observableArray. 
observableArray provides the pop, push, shift, unshift, reverse, sort, splice remove & removeAll functions to manipulate the property.


Examples for the all three main properties of KnockoutJS are given below.


Happy coding...