📜  可观察的:KnockoutJS

📅  最后修改于: 2021-05-20 05:21:46             🧑  作者: Mango

可观察物简介:
通过用户交互动态更改的特殊对象属性,可以通知订户有关更改并自动检测依赖关系。

特征:
读写可观察物
1.读取– AppViewModel.yourName();
2.写– AppViewModel.yourName(’Diana’);
3.写多个– AppViewModel.yourName(’Diana’)。yourAge(25);

定义一个可观察的对象(包括示例):

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. 

好处:

  • 他们可以自动检测依赖关系。
  • 他们能够通知订户有关更改。