BootstrapTable and KnockoutJS are combined to implement addition, deletion, modification, and query functions [1]. bootstrapknockoutjs

Source: Internet
Author: User
Tags tojson

BootstrapTable and KnockoutJS are combined to implement addition, deletion, modification, and query functions [1]. bootstrapknockoutjs

Bootstrap is a front-end framework that frees Web developers and shows a very high level of UI. Theoretically, you do not need to write a line of css. You only need to add the appropriate attributes to the tag.

KnockoutJS is a JavaScript-implemented MVVM framework. Great. For example, after adding or removing list data items, you do not need to refresh the entire control segment or write JS add or delete nodes by yourself. You only need to pre-define the template and attributes that comply with its syntax definition. Simply put, we only need to pay attention to data access.

1. Introduction to Knockout. js

1. Knockout. js and MVVM

Nowadays, various front-end frameworks are overwhelmed and dazzled. Sometimes I have to lament that as a programmer, there are always endless technologies that will come to an end unless you turn them into one! It's up to you to decide whether to look back or not!

Knockout. js is a lightweight front-end framework based on the MVVM mode. How light is it? Based on the latest version v3.4.0 shown on the official website, it is only 22kb. The ability to handle data model and interface DOM binding in a friendly manner, the most important thing is that its binding is bidirectional, that is, the data model has changed, the data on the Interface DOM also changes. In turn, the data on the Interface DOM changes, and the data model changes accordingly. This greatly reduces the amount of front-end code and makes the interface easy to maintain. We no longer need to write a lot of event monitoring data models and DOM changes on the interface. The following bloggers will describe these two points based on an instance.

Knockout. js Official Website: http://knockoutjs.com

Knockout. js Open Source Address: https://github.com/knockout/knockout

MVVM mode: This is a design mode for creating user interfaces. MVVM splits it into three modules: Model, View, and ViewModel. Model is the data Model, and View is our View, viewModel is a view model used to bind the data model to the dom element on The View. If you have used WPF and Silverlight, understanding this should not be a problem. If you have not used it, it also has a relationship. After reading this article, you will have a general understanding.

2. Simplest instance

Generally, if you use Knockout. js from scratch, you need to do at least four

2.1,Download the knockout. js file from the official website and reference it to the view page.

<script src="~/scripts/knockout/knockout-3.4.0.min.js"></script> 

Note: knockout. js does not require jquery support. If your project requires jquery-related operations, you can reference jquery; otherwise, you can only reference the above files.

2.2,Define ViewModel

What is viewmodel? In js, it looks like a json object. We define a viewmodel:

Var myViewModel = {Name: "Lilei", risk sion: "software engineer ",};

2.3,The data-bind tag is defined in the view.

<Div> Name: <label data-bind = "text: Name"> </label> <br/> occupation: <input type = "text" data-bind = "textinput: sion Sion"/> </div>

Note: The text corresponding to the input tag must use textinput, while the text of the common tag can use text.

2.4 activate binding

After completing the preceding three steps, you also need to activate the knockout binding.

ko.applyBindings(myViewModel); 

To achieve this, we basically implement the data binding of the simplest viewmodel. Expected results:


If you are careful enough, you will find that the ko. applyBindings () method has two parameters. The first is the viewmodel we need to bind, and the second is what? Ko. applyBindings (myViewModel). We can see that the second parameter is an optional parameter, which indicates the scope of the tag bound to the viewmodel. For example, let's change the above Code:

<Div> Name: <label id = "lb_name" data-bind = "text: Name"> </label> <br/> occupation: <input type = "text" data-bind = "textinput: partition Sion"/> </div> ko. applyBindings (myViewModel, document. getElementById ("lb_name "));

Expected result:


Therefore, the second parameter limits the scope of myViewModel, that is, binding takes effect only on the id = "lb_name" tag. If the second parameter is a container tag such as div, it indicates that the bound range is all sub-labels under the div.

3. Monitoring attributes

As of the above four steps, we cannot see any effect. What we see is simply binding the data of a json object to the html Tag. What is the significance of this? Didn't it complicate simple problems? Don't worry. Witness the miracle now! As mentioned above, the most important significance of knockout is bidirectional binding. How can we implement bidirectional binding? The answer is monitoring properties.

In knockout, the core has three monitoring attributes: Observables, DependentObservables, ObservableArray, and Observe, if the observed attribute or observed attribute does not feel appropriate, we are currently called a monitoring attribute.

3.1. Observables: Monitoring Properties

Let's change the example above to the following:

<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> 

Ko. observable ("Lilei") is to add the Name attribute of viewmodel to the monitoring attribute, and change a certain Name attribute to the monitoring attribute. This magic happens, let's see when we write myViewModel. when:

The Name is changed from the original attribute to the method, that is, once ko is added. observable (), then the corresponding attribute will become a method, so the value and value assignment of Name must use myViewModel. name. Let's take a look at the effect:

Code: Obviously, myViewModel. name ($ (this ). val (); this sentence assigns the value of the current text box to the Name attribute. Because the interface is bound with the Name attribute, the value in the label also changes. You can also use the textchange event. You only need to assign the value of the current text box to the label to achieve this effect. This is nothing. Indeed, your writing can also achieve the goal, but the significance of our monitoring attribute is that the value of Name changes anywhere, and the interface will change accordingly, instead of assigning values to the label everywhere, you only need to set the focus Method myViewModel in JS. name. Is it amazing ~~

3.2. DependentObservables: monitor dependency attributes

If you have read the monitoring attributes above, are you not satisfied? Next let's take a look at the use of monitoring dependency attributes.

Let's take a look at the code again:

<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> 

Let's take a look at the effect:


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.

3.3. ObservableArray; Monitoring Array

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!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.