Code: add the metric dependency attribute ko. dependentObservable () can monitor the change of the Des attribute value at the same time to the change of Name and transition sion. If any of the changes, the tag bound to the Des will trigger the change, the biggest benefit of doing so is to avoid the trouble of using JavaScript to operate dom.
In addition to the above two types, ko also supports monitoring array objects. Let's look at an example:
<Head> <meta name = "viewport" content = "width = device-width"/> <title> Index3 </title> <script src = "~ /Scripts/jquery-1.9.1.min.js "> </script> <script src = "~ /Scripts/knockout/knockout-3.4.0.min.js "> </script>
See the results:
Code: ko. the observableArray () method adds the monitoring of the array object. That is to say, any change to the array of the deptArr array object in js will trigger the UI. It should be noted that the monitoring array is actually the monitored array object, and the sub-object attribute in the array object is changed and cannot be monitored. For example, we change the click event to the following:
$(function () {$("#btn_test").on("click", function () {deptArr[1].Name = "aaa";});});
Effect:
Therefore, array monitoring actually monitors the array object and does not monitor the attribute changes of elements in the array. If you need to monitor the attribute changes of objects in the data, you need to use ko. observable () for the object attributes in the data. If you are interested, try it.
4. Common data-bind attributes in ko
In the previous article, we used multiple data-bind attributes. How many data-bind attributes are there in knockout. Here we list some common attributes.
4.1, text and inputText
Text, as the name implies, is the meaning of text. This binding attribute is generally used for <label>, <span>, <div>, and other labels to display text. Of course, if you want, you can use this binding for any tag. It is basically easy to say. If ko. observable () is not used, it is static binding; otherwise, it is dynamic binding.
InputText: the text of the input tag, which is equivalent to the value attribute of the input tag.
<Div> Name: <label data-bind = "text: Name"> </label> <br/> occupation: <input type = "text" data-bind = "textinput: sion Sion"/> </div> // 1. define ViewModelvar myViewModel = {Name: ko. observable ("Lilei"), isolation sion: "software engineer",}; // 2. activate binding ko. applyBindings (myViewModel );
4.2. value
This binding property is generally used for the input tag, which is similar to the inputText above. But the value is more standard.
ValueUpdate is another parameter used with value, which indicates when to update the value on the interface. ValueUpdate has the following values: change, keyup, keypress, and afterkeydown. The value of viewmodel corresponding to the value is updated during operations such as text change, keyboard shrinking, keyboard pressing, and keyboard pressing.
Name: <input type = "text" data-bind = "value: Name, valueUpdate: 'keyup'"/> <br/> var myViewModel = {Name: ko. observable ("Lilei"),}; // 2. activate binding ko. applyBindings (myViewModel );
The above code updates the value Attribute of the text box and the Name attribute of myViewModel when the keyboard is collapsed.
4.3. checked
Checked binding is generally used for checkbox, radio, and other form elements that can be selected. The corresponding value is of the bool type. Similar to the usage of value, it is not repeated.
4.4. enable
Enable binding is generally used to enable or disable label elements. In contrast to disabled, the corresponding value is of the bool type.
<Div> <input type = "text" data-bind = "enable: IsMen"/> </div> <script type = "text/javascript"> // 1. define ViewModelvar myViewModel = {Name: ko. observable ("Lilei"), partition sion: ko. observable ("software engineer"), Age: ko. observable (40), IsMen: ko. observable (true)}; // 2. activate binding ko. applyBindings (myViewModel); myViewModel. isMen (false); </script>
Because the IsMen attribute is set to false, all corresponding text boxes are disabled.
4.5. disabled
Unlike enable, enable is used in a similar way.
4.6. options
In the preceding section, options is used for binding the select statement. options indicates the option set of the select label. The corresponding value is an array, indicating the data source in the drop-down box. You can use observableArray to enable monitoring of this data source. See the preceding figure for usage.
4.7. html
Text binding is actually the setting and value of the label innerText. Similarly, html binding is also the setting and value of innerHTML. It corresponds to an html Tag.
4.8. css
Css binding adds or deletes one or more styles (classes) to DOM elements. Format:
<Style type = "text/css">. testbold {background-color: powderblue;} </style> <div data-bind = "css: {testbold: myViewModel. name () = 'lilei'} "> aaaa </div> var myViewModel = {Name: ko. observable ("Lilei"), partition sion: ko. observable ("software engineer"), Age: ko. observable (40 )};
This div displays the background color.
If you want to add or remove multiple styles, you only need to change them slightly. For example:
<Div data-bind = "css: {testbold: myViewModel. name () = 'lilei', testborder: myViewModel. sion () = 'php engineer'} "> aaaa </div>
4.9. style
If the function of css binding is to dynamically add or remove class styles to tags, the function of style binding is to dynamically add or remove a style tag. For example:
<div data-bind="css:{background-color:myViewModel.Name()=='Lilei'?'red':'white'}">aaaa</div>
If you want to add or remove multiple css bindings
4.10. attr
Attr binding is used to remove one or more attributes (including Custom Attributes) from a tag. It is similar to css.
4.11. click
Click binding adds the execution method of click events on the corresponding DOM element. It can be used on any element.
<Div> <input type = "button" value = "test click binding" data-bind = "click: ClickFunc"/> </div> var myViewModel = {ClickFunc: function () {alert ($ (event. currentTarget ). val () ;}}; ko. applyBindings (myViewModel );
Event. currentTarget indicates the currently clicked DOM element. Sometimes for convenience, we can directly bind anonymous functions, such:
<Div> <input type = "button" value = "test click binding" data-bind = "click: function () {alert ('clicked ');} "/> </div>
However, this style of JavaScript code in html makes it difficult for bloggers to accept and maintain the Code, especially when the logic in click events is slightly complicated. Therefore, it is not recommended to directly write this anonymous function unless necessary.
4.12 others
For details about all data-bind bindings, refer to the official website. We will not list them here. You can check it on the official website when you need it. Take a look at all the bindings listed on the official website:
5. Conversion and relationship between Json objects and monitoring attributes
We know that, in order to avoid direct display in different languages, we normally use Json format data for frontend and backend interaction. We use the data model obtained from the backend through http requests, to use some of our ko features, we must convert these common data models into ko's monitoring attributes. In turn, we use ko's monitoring attributes, sometimes we need to convert these attributes into common json data to the backend. How can we achieve this conversion?
5.1 convert a JSON object to a ViewModel
For example, we get a Json object from the background, convert it to our viewmodel, and then bind it to our interface DOM.
$.ajax({url: "/Home/GetData",type: "get",data: {},success: function (data, status) {var oJson = data;}});
We send a request to the backend, get a json object, assign a value to oJson, and then convert oJson to viewmodel. The most intuitive way is to manually convert it. For example, we can:
var myViewModelJson = {DeptName: ko.observable(),DeptLevel: ko.observable(),DeptDesc:ko.observable()};ko.applyBindings(myViewModelJson);
Then in the success of the ajax request
success: function (data, status) {var oJson = data;myViewModelJson.DeptName(oJson.DeptName);myViewModelJson.DeptLevel(oJson.DetpLevel);myViewModelJson.DeptDesc(oJson.DeptDesc);}
In this way, the binding of json objects to viewmodel is realized through manual binding. The advantage of doing so is flexibility, the disadvantage is obvious, and the amount of manual code is too large.
Fortunately, there is a omnipotent open source, and some people always think of a better way. We can use the knockout. Mapping component to help us to convert json objects to viewmodel on the interface.
Knockout. Mapping Open Source Address: Download
The following is a simple example of how to use it. We do not need to define any viewmodel. First, we need to reference knockout. mapping. js.
<script src="~/scripts/knockout/knockout-3.4.0.min.js"></script><script src="~/scripts/knockout/extensions/knockout.mapping-latest.js"></script>
Note: Here knock. mapping-lastest.js must be placed behind the knockout-3.4.0.min.js, otherwise ko. mapping is not called.
And then use it directly in the success function.
success: function (data, status) {var myViewModelJson2 = ko.mapping.fromJS(data);ko.applyBindings(myViewModelJson2);}
Let's look at the effect:
Code: json objects retrieved from the background through ajax requests can be easily converted to viewmodel through ko. mapping. fromJS! In addition to this usage, you can also update the viewmodel that already exists, using the following:
var myViewModelJson = {DeptName: ko.observable(),DeptLevel: ko.observable(),DeptDesc:ko.observable()};ko.applyBindings(myViewModelJson);$(function () {$.ajax({url: "/Home/GetData",type: "get",data: {},success: function (data, status) {ko.mapping.fromJS(data, myViewModelJson)}});});
In success, update the viewmodel myViewModelJson based on the data value.
5.2 convert ViewModel to JSON object
As mentioned above, the JSON object is converted to viewmodel. In turn, what should we do if we need to convert viewmodel to Json object and pass it to the backend?
Two methods are provided in knockout:
• Ko. toJS (): converts viewmodel to a JSON object
• Ko. toJSON (): converts viewmodel to a serialized Json string.
For example, our code is as follows:
$ (Function () {var oJson1 = ko. toJS (myViewModelJson); var oJson2 = ko. toJSON (myViewModelJson);}); var myViewModelJson = {DeptName: ko. observable ("R & D department"), DeptLevel: ko. observable ("2"), DeptDesc: ko. observable ("developers")}; ko. applyBindings (myViewModelJson );
Then we can monitor the values of oJson1 and oJson2:
Code: Through the above figure, it is easy to understand the differences between the two methods. here we need to note that these two methods are included in ko and do not need the support of the mapping component.
6. Create your own data-bind attributes
As mentioned above, some bindings and monitoring in knockout are introduced. In some cases, we need to customize our data-bind, such: <label data-bind = "myBind: Name"> </label>: this requirement is especially useful when encapsulated components. Can it be implemented? Of course.
In knockout, the ko. bindingHandlers attribute is provided to customize the data-bind attribute. Its syntax is as follows:
ko.bindingHandlers.MySelect = {init: function (element, valueAccessor, allBindingsAccessor, viewModel) {},update: function (element, valueAccessor, allBindingsAccessor, viewModel) {}};
In this way, we can use custom data-bind in our html Tag.
<Div> <select data-bind = "MySelect: $ root "> <option id =" 1 "> R & D department </option> <option id =" 2 "> HR department </option> <option id =" 3 "> Administration Department </option> </select> </div>
MySelect is our custom binding attribute. $ root can be understood as initialization for the moment (although this explanation is not rigorous, please correct it if you have a more reasonable explanation ).
Code explanation: the ko. bindingHandlers above can be used to easily implement custom binding attributes. Note the following two points:
• Init, as its name implies, initializes the custom binding. It contains multiple parameters. Generally, the first two parameters are used. The first parameter indicates initializing the DOM elements bound to the custom binding, the second parameter is generally used to pass the initialization parameter.
• Update and update callback. This method is used when the corresponding monitoring attribute changes. If callback is not required, this method is not declared.
Here, the blogger will briefly describe the use of the custom binding by combining the MutiSelect, a drop-down box component that was previously shared.
6.1. Simplest MutiSelect
In general, if we need to use ko to encapsulate some common components, we need to use ko. bindingHandlers. The following bloggers will explain how to use the MutiSelect component.
First declare the custom ko. bindingHandlers and initialize our select tag in the init method.
ko.bindingHandlers.MySelect = {init: function (element, valueAccessor, allBindingsAccessor, viewModel) {$(element).multiselect();},update: function (element, valueAccessor, allBindingsAccessor, viewModel) {}};
Then use
<Div style = "text-align: center;"> <select data-bind = "MySelect: $ root "> <option id =" 1 "> R & D department </option> <option id =" 2 "> HR department </option> <option id =" 3 "> Administration Department </option> </select> </div>
Part 3: Activate binding
$(function () {var MultiSelect = {};ko.applyBindings(MultiSelect);});
If you do not need to pass parameters, you only need to bind an empty viewmodel. Some people are confused. The third part is meaningless. The blogger understands that the DOM element needs to use data-bind to bind data, and the ko. applyBindings () must be enabled ().
Expected results:
6.2 parameter transfer
Step 1: Customize ko. bindingHandlers
ko.bindingHandlers.MySelect = {init: function (element, valueAccessor, allBindingsAccessor, viewModel) {var oParam = valueAccessor();$(element).multiselect(oParam);},update: function (element, valueAccessor, allBindingsAccessor, viewModel) {}};
Step 2 is the same as above. Use this custom binding in the html Tag.
Step 3: input parameters when activating binding
$ (Function () {var MultiSelect = {enableClickableOptGroups: true, // hide group onChange: function (option, checked) {alert ("select change") ;}}; ko. applyBindings (MultiSelect );});
The parameters can be uploaded to the initialization of MutiSelect through these three steps:
Code explanation: the second parameter of the init event. As we have said, it mainly serves to obtain the parameters passed in our viewmodel, but it should be used as a method here, why is it so useful? It is still to be studied!
2. add, delete, modify, and query instances
At this point, the basic things have finally been paved the way. I was going to solve it in one article, but I didn't expect that the basic things would have been so much space! Add, delete, modify, and query examples in the next article BootstrapTable and KnockoutJS are combined to implement the add, delete, modify, and query function [2]. You are welcome to learn and exchange. Of course, you are also welcome to recommend this function!