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.


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.




Article Tags :

2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.