The book goes back to the previous discussion of the view model can be defined in the normal observable property and the Observablearray property implementation and UI elements of the two-way binding, this section we continue to explore the third kind of binding property types: Computed observables, I call it computational observable (honestly, I'm not sure about observable how to translate).
What if you have defined a observable property called FirstName and a observable attribute called LastName in the View object, and you want to display the person's full name? In this case, it's time for computed observables to debut-they are a way of relying on other observables. And when the dependent observables changes, it automatically updates the content. Here's a demo:
function Appviewmodel () { this. FirstName = ko.observable (' Bob '); this. LastName = ko.observable (' Smith ');}
At this point you can add a computed observable to display the full name
function Appviewmodel () { this. FullName = ko.computed (function() { return this This . LastName (); This );}
Then bind the UI like this
<data-bind= "Text:fullname"></span >
After binding, FullName automatically updates to the most recent value, regardless of when the FirstName or LastName has changed. (That is, when the dependent observable changes, the activation functions placed in computed are called every time, and whatever you return will be passed to the appropriate observer, such as UI elements or other computed observables).
Dependency Chain
Of course, you can also create a computed observables chain, such as a scenario like this:
- A observable property called items that represents a series of objects
- Another observable property called Selectedindexes, which represents the index of the following table for the item selected by the user
- A computed observable called SelectedItems, which returns an array of objects related to SelectedIndex.
- Another computed observable, which returns TRUE or FALSE, returns true if there is a value in the SelectedItems array. Some UI elements, such as button, are available depending on the return value of the computed observable.
Modify items
or selectedIndexes
ripple and update the computed observables in the chain, which in turn updates the UI elements bound to them.
About ' this '
The second parameter in ko.computed (in the example above this
) defines what this is exactly when the computed observable function is called. If you do not pass this value, you cannot reference This.firstname or This.lastname as you would in your code. The programmer of the experienced JavaScript should not have any doubts, because in computed observable, this refers to the Appviewmodel object,
You will not be able to access the properties inside, so you need to re-define the assignment. JavaScript looks strange at this point. (like C # and Java, you never want the programmer to assign a value to this, but JavaScript needs it because its functions itself doesn't belong to any object by default.) )
- A popular and simple way to do this is to avoid always thinking about the context of this, and if your view model's constructor copies a reference of this to a separate variable (the classic can be called
self
), you can use it anywhere else you need to use this. , you don't have to worry about this being implicitly defined as another object, for example:
function Appviewmodel () { varthis; = ko.observable (' Bob '); = ko.observable (' Smith '); = ko.computed (function() { return self.firstname () + "" + Self.lastname (); });}
因为self是在function中被捕获的
, he will always be available in internal functions, such as the execution function of computed observable.
PureComputed observables
If your computed observable only performs a simple calculation and returns a value that relies on other observable, then it is better to declare this ko.pureComputed
instead of one ko.computed。例如
:
this. FullName = ko.purecomputed (function() { returnthis this this);
From this computed declaration to Pure (if its calling method does not directly change the state of other objects), Knockout can more effectively manage how it is reactivated and how its memory is used. When no other code is dependent on this property, knockout will automatically suspend or release it. (That is, there is a performance optimization)
Prevent computed observables from always notifying subscribers
When a computed observable returns a base type value (number, String, Boolean, or null), it is usually only notified when it actually changes, if the same value is always returned. Then you will not receive a notification. However, you can use the built-in notify
Extender to ensure that subscribers to a computed observable ' s can always receive notifications when computed observable updates, even if the updated values are the same as before. Use the following methods:
Myviewmodel.fullname = ko.purecomputed (function() { return myviewmodel.firstname () + "+' Always '}");
Delayed Update Notification
for (var in myObject) { if (Myobject.hasownproperty (prop) &&! ) Ko.iscomputed (Myobject[prop])) { = Myobject[prop]; }}
Typically, a computed observable is updated to notify its subscribers immediately. But if a computed observable has a lot of dependencies and updates it will be time consuming, you can get a better performance by limiting the interval between updates. This can be done in the following ways:
MyViewModel.fullName.extend ({ratelimit:50});
Determine if a property is a computed observable
In some scenarios, it is useful to programmatically determine whether a property is computed observable. Knockout provides a tool method, ko.isComputed
for example, when you send data to a background service, you may want to exclude computed observables from the submission data. Can do this:
for (var in myObject) { if (Myobject.hasownproperty (prop) &&! ) Ko.iscomputed (Myobject[prop])) { = Myobject[prop]; }}
In addition, Knockout provides a number of similar methods to operate on observables and computed observables:
When computed observable is used only in your UI type
If you only need to use the composite full name on your UI interface, you can declare it as follows:
function Appviewmodel () { This function () { returnthis. LastName ();} ;}
Now your UI binding becomes a method call, as follows:
<data-bind= "Text:fullname ()"></span >
Knockout creates the computed observable behind the scenes to monitor what observables the binding expression relies on, and automatically releases the associated element if it is deleted later (Dispose it).
All right, the next section continues!
Knockoutjs official website Translation Series (iii) use computed observables