Observables : KnockoutJS
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.
Recommended Posts:
- Introduction to KnockoutJS
- Reduce the number to minimum multiple of 4 after removing the digits
- jQuery UI | Tooltip
- CSS | fit-content() Property
- jQuery UI | Tabs
- How to change the placeholder text using jQuery?
- How to perform wordpress security auditing?
- Angular 4 | Introduction
- PHP | Imagick roundCorners() Function
- PHP | ReflectionClass isUserDefined() Function
- PHP | ReflectionClass isTrait() Function
- PHP | ReflectionClass isSubclassOf() Function
- PHP | Imagick resizeImage() Function
- What is web socket and how it is different from the HTTP?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


