Open In App

Observables : KnockoutJS

Improve
Improve
Like Article
Like
Save
Share
Report

INTRODUCTION TO OBSERVABLES:

Special Object Property that changes dynamically through User Interaction, can notify subscribers about changes and automatically detect dependencies.

FEATURES:

Reading and Writing Observables 1. READ – AppViewModel.yourName(); 2. WRITE – AppViewModel.yourName(‘Diana’); 3. WRITE MULTIPLE – AppViewModel.yourName(‘Diana’).yourAge(25);

DEFINING AN OBSERVABLE (WITH EXAMPLES):

1. Creating an Observable Variable - 

var myObservable = ko.observable();
myObservable('Hello');
alert(myObservable());

Assign ko.observable function to a variable. Knockout then converts the variable
into a function and tracks when the value changes to notify the UI elements
associated with the variable.

2. Creating an Observable Array -

var myObservableArray = ko.observableArray([]);
myObservableArray.push('Hello');

Array is instantiated as an empty array, passing square brackets in the
constructor.
When the elements are added or removed from the array, Knockout notifies
elements that are subscribed to the notifications.

3. Creating a Computed Observable -

self.firstName = ko.observable('Steve');
self.lastName = ko.observable('Kennedy');
self.fullName = ko.computed(function() {
return 'Hello ' + self.firstName() + ' ' + self.lastName(); });

When the ViewModel is bounded to the Knockout, the computed function is executed
then, it subscribes to any change events to that variable and hence Knockout
updates the computed variable as well.

ADVANTAGES:

  • They can automatically detect dependencies.
  • They are able to notify the subscribers regarding the changes.

Last Updated : 01 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads