Assignable Calculation Monitoring Properties
Assignable calculation monitoring properties are very professional, generally not available in most cases, beginners can skip this section
Typically, the computed monitoring properties are generally read-only . We can make the computed monitoring property into an assignable state by using our own callback function.
You can use your own custom logic to make the computed monitoring properties writable. Just like an empty property, you can use the syntax of a link to a model object to assign a value . For example, myViewModel.fullName(‘Joe Smith‘).age(50)
.
Example 1: Decomposition with user input
Let's go back to the classic example of "first name + last name = Full Name" For example, FullName is a computed monitoring attribute that allows the user to edit the full name directly, and then parse and assign values to the two monitoring properties of FirstName and LastName, respectively, based on the full name entered by the user.
First Name:Last Name:Hello,
UI Source code:
<Div>First Name:<spanData-bind= "Text:firstname"></span></Div><Div>Last Name:<spanData-bind= "Text:lastname"></span></Div><Divclass= "Heading">Hello,<inputData-bind= "Textinput:fullname"/></Div>
View Model Code:
functionMyviewmodel () { This. FirstName = ko.observable (' Planet '); This. LastName = ko.observable (' Earth '); This. FullName =ko.purecomputed ({read:function () { return This. FirstName () + "" + This. LastName (); }, write:function(value) {varLastspacepos = Value.lastindexof (""); if(Lastspacepos > 0) {//Ignore values with no space character This. FirstName (value.substring (0, Lastspacepos));//Update "FirstName" This. LastName (Value.substring (Lastspacepos + 1));//Update "LastName"}}, Owner: This });} Ko.applybindings (NewMyviewmodel ());
In this example, the read and write fallback functions of purecomputed (which can also use computed) are used, where the write-back function parses the computed monitoring properties and assigns them to the two monitoring properties of FirstName and LastName, respectively.
Example 2: Select or cancel an item
Not to be continued. Dinner's gone.
Knockoutjs 3.X API Third Chapter Computing Monitoring properties (2) Assignable calculation monitoring properties