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
- Length of the longest subsegment which is UpDown after inserting atmost one integer
- Chrome Inspect Element Tool & Shortcut
- How to get the last item of JavaScript object ?
- What happens inside JavaScript Engine ?
- How to detect value change on hidden input field in JQuery ?
- How to make CSS Loader ?
- How to view array of a structure in JavaScript ?
- Laravel | Directory Structure
- Client-Server Model
- How to stop browser back button using JavaScript ?
- Local File Inclusion (LFI)
- How to turn on/off form autocompletion in HTML ?
- What are the differences and Similarities Between Lumen and Laravel?
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.



