Bootstraptable+knockoutjs implementation of adding and deleting solutions
Foreword: For some reason, need to learn the next knockout.js, this component was heard earlier, but has not tried to use, this two days study, think it really good, two-way binding mechanism is simply too cool. Today intends to combine bootstraptable and knockout to achieve a simple deletion and modification, to experience a magical mvvm. About the remainder of the Webapi, Bo Master must take time to fill up.
I. Introduction to Knockout.js 1, knockout.js and MVVM
Now, a variety of front-end frame overwhelmed, dazzling, sometimes have to sigh as a program ape is also really bitter force, always have to learn the technology, when is the end, unless you convert! Struck, back is not the shore, by you decide!
Knockout.js is a lightweight front-end framework based on the MVVM pattern, how light is it? According to the latest version shown on the official website v3.4.0, only 22kb. To be able to handle the data model and interface DOM binding, most importantly, its binding is bidirectional, that is to say, the data model changes, the interface DOM data will also change, in turn, the interface DOM data changes, the data model will be corresponding to this change. This greatly reduces our front-end code volume and makes our interface easy to maintain, without having to write a lot of events to monitor the data model and interface DOM changes. The blogger will explain these two points according to a usage example.
Knockout.js Official website: http://knockoutjs.com
Knockout.js Open Source Address: https://github.com/knockout/knockout
MVVM mode: This is a design pattern that creates a user interface, and MVVM splits it into three blocks, which is the model, view, Viewmodel,model, and the data models, view is our views, and ViewModel is a view model. Used to bind the DOM elements above the data model and view. If you have used WPF and Silverlight to understand that this should not be a problem; you will have a general idea of what you have done without using it.
2. The simplest example
In general, if you use knockout.js from scratch, you need to do at least four of the following
2.1, go to the official website to download the Knockout.js file, and then refer to the View page inside.
<script src= "~/scripts/knockout/knockout-3.4.0.min.js" ></script>
Note: Knockout.js does not require jquery support, and if your project requires jquery, refer to jquery, or simply refer to the above file.
2.2. Define ViewModel
What is ViewModel? In fact, in JS, it looks like a JSON object. We define a ViewModel:
var Myviewmodel = { Name: "Lilei", profession: "Software Engineer", };
2.3. Define the label of the binding data-bind in the view
<div> Name: <label data-bind= "Text:name" ></label><br/> Occupation: <input type= "Text" data-bind= "Textinput:profession"/> </div>
Note: The text of the input tag needs to be textinput, and the text of the normal label can be used.
2.4. Activating bindings
To do the above three steps, you also need to activate the knockout bindings
Ko.applybindings (Myviewmodel);
To achieve these four parts, the basic implementation of a simple viewmodel data binding. Get results:
If you are careful enough, you will find that the Ko.applybindings () method has two parameters, the first one is the ViewModel we need to bind, and what is the second one? by Ko.applybindings (Myviewmodel), the second parameter is an optional parameter that represents the scope of the ViewModel bound label, for example, we change the above code:
<div> Name: <label id= "Lb_name" data-bind= "Text:name" ></label><br/> Occupation: <input Type= "text" data-bind= "textinput:profession"/> </div>
Ko.applybindings (Myviewmodel,document.getelementbyid ("Lb_name"));
Get results:
Thus: The second parameter limits the scope of the Myviewmodel, that is, only the id= "lb_name" label above the binding will take effect, if the second parameter is a div, such as a container label, it indicates that the scope of the binding is all sub-tags under the div.
3. Monitoring properties
As of the four steps above, we don't see any effect, we see nothing more than to bind the data of a JSON object to the HTML tag, so what's the point? Isn't it complicated with simple questions? Don't worry, witness the miracle now! As stated above, the most important point of knockout is the two-way binding, so how do we implement our two-way binding? The answer is monitoring properties.
Inside the knockout, the core has three monitoring properties:Observables,dependentobservables,observablearray, the meaning of observe is to be observed and observed, If the observation attribute or the observation attribute is not felt properly, we call the monitoring attribute.
3.1. Observables: Monitoring Properties
Let's change the above example to this:
The meaning of ko.observable ("Lilei") is to add the Name property of ViewModel as the Monitoring property, the Name property becomes the Monitoring property, the magic thing happens, let's see when we write Myviewmodel.:
The name is changed from the original attribute to the method, that is, once the ko.observable () is added, the corresponding property becomes the method, and the value and assignment of the name need to be handled using Myviewmodel.name (). Let's start by looking at the effect:
Code Explanation: Obviously myviewmodel.name ($ (this). Val ()); This sentence assigns the value of the current text box to the Name property, and the value inside the label changes as the interface binds the Name property. Or you would say, this can be done using the TextChange event, as long as the value of the current text box is assigned to the label label, you can also achieve this effect, this is nothing. Indeed, your writing can also achieve the purpose, but the significance of our monitoring property is that any place change the value of Name, the interface will change, instead of each place to assign a label label, JS inside only need to focus on the method Myviewmodel.name () above can. is not very good ~ ~
3.2. Dependentobservables: Monitoring Dependency propertiesWhat if we look at the monitoring properties above? Let's take a look at the use of monitoring dependency properties.
Let's change the code to look at:
First look at the effect:
Code explanation: By adding a monitoring dependency property ko.dependentobservable () will be able to monitor the value of the Des property at the same time to the name and profession two changes, any one of which changes, the DES binding label will trigger the change, The biggest advantage of this is to avoid the JS to operate the DOM of trouble, a bit of meaning.
3.3, observablearray; monitoring arraysIn addition to the above two types, KO also supports the monitoring of array objects. Let's look at an example:
Look at the effect:
Code Explanation: The above through Ko.observablearray () This method adds the monitoring of the array object, that is, the JS inside any place as long as the Deptarr array object has been changed, the UI will trigger the corresponding. It is important to note that the monitoring array is actually the monitored array object itself, which is not monitored for changes in the properties of the sub-objects inside the array object. For example, we changed the click event to this:
$ (function () { $ ("#btn_test"). On ("click", Function () { deptarr[1]. Name = "AAA"; });
Effect:
As a result, array monitoring is actually monitored by the array object itself, which does not monitor the property changes of the elements inside the array. If you do need to monitor the object's property changes in the data, you need to use ko.observable () for the object properties in the data. If you are interested, try it.
4, KO inside the common data-bind propertiesIn the above, we used multiple data-bind properties, so how many of these data-bind properties are there in knockout? Here we list some of the commonly used properties.
4.1. Text and InputtextText, as the name implies, is the literal meaning, this binding property is commonly used for <label>, <span>, <div> and other label display text, of course, if you want, any tag can use this binding. It is used basically nothing to say. If Ko.observable () is not used, it is a static binding, otherwise dynamic binding.
The text of the Inputtext,input label, which corresponds to the Value property of the input tag.
<div> Name: <label data-bind= "Text:name" ></label><br/> Occupation: <input type= "Text" data-bind= "Textinput:profession"/> </div>
1. Define ViewModel var Myviewmodel = { Name:ko.observable ("Lilei"), Profession: "Software Engineer", }; 2. Activate bind ko.applybindings (Myviewmodel);
4.2. ValueThis binding property is typically used for input tags, and is basically similar to the inputtext above. Only value is more canonical.
Also used with value is a parameter, Valueupdate, which indicates when the interface is doing something to update the value. Valueupdate main value has Change/keyup/keypress/afterkeydown and so on. The values for the ViewModel of value correspond to changes in text, keyboard indentation, keyboard presses, keyboard presses, and so on.
Name: <input type= "text" data-bind= "value:name,valueupdate: ' KeyUp '"/><br/>
var Myviewmodel = { Name:ko.observable ("Lilei"), };//2. Activating binding ko.applybindings (Myviewmodel);
The code above indicates that the keyboard is updated to update the text box's Value property and Myviewmodel's Name property.
4.3, checkedChecked bindings are typically used for form elements that can be checked, such as checkbox, Radio, and the corresponding value is the bool type. And the use of value is basically similar, do not repeat the explanation.
4.4. EnableThe enable binding is typically used to enable and disable the label element, which is typically used for form elements. In contrast to disabled, the corresponding value is also of type bool.
<div> <input type= "text" data-bind= "Enable:ismen"/> </div> <script type= "text/ JavaScript > //1. Define ViewModel var Myviewmodel = { Name:ko.observable ("Lilei"), Profession: Ko.observable ("Software Engineer"), Age:ko.observable (+), IsMen:ko.observable (True) }; 2. Activate bind ko.applybindings (Myviewmodel); Myviewmodel.ismen (false); </script>
Because the Ismen property becomes false, all corresponding text boxes are displayed in a disabled state.
4.5, disabledIn contrast to enable, usage and enable are similar.
4.6. OptionsThe options are used in the previous binding with Select, which represents the set of option for the select tag, and the corresponding value is an array representing the data source for the drop-down box. You can use Observablearray to enable monitoring of this data source. usage See above.
4.7. htmlThe text binding is actually the setting and the value of the label innertext, so the HTML binding is also the setting and value of the innerHTML. It corresponds to a value of an HTML tag.
4.8. cssA CSS binding is to add or remove one or more styles (class) onto a DOM element. Use 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"), Profession:ko.observable ("software Engineer"), Age:ko.observable (+) };
The div will display the background color.
If you need to add or remove more than one style, just change it slightly, such as:
<div data-bind= "css:{testbold:myviewmodel.name () = = ' Lilei ', testborder:myViewModel.Profession () = = ' php engineer '} ' >aaaa</div>
4.9. StyleIf the role of CSS binding is to dynamically add or remove class styles to tags, the role of the style binding is to dynamically add or remove a style from the tag. Like what:
<div data-bind= "css:{padding:0px; Color:rgb (0, 0, 255); line-height:1.5!important;" >>aaaa</div>
If you are adding or removing more than one, use the same CSS bindings
4.10, attrATTR bindings are primarily used to remove one or more properties (including custom attributes) from a tag, and Yonghe is similar to CSS.
4.11. ClickThe click Binding represents an execution method that adds a click event above the corresponding DOM element. 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 represents the currently clicked DOM element. Sometimes for simplicity, we bind directly using anonymous functions, such as:
<div> <input type= "button" value= "Test click Bind" data-bind= "Click:function () { alert (' clicked '); }"/ > </div>
However, this kind of JS kneading into the HTML inside the wording of the blogger is difficult to accept, and feel relatively inconvenient to maintain, especially in the Click event logic is slightly more complex. Therefore, if not necessary, it is not recommended to write this anonymous function directly.
4.12. OtherAbout Data-bind All the bindings, you can crossing the above introduction, here is not listed. Need to use the time to go to the official web check on the good. Look at all the bindings listed on the official website:
5. Conversion and relationship of JSON objects and monitoring attributesWe know that in order to avoid the direct presentation of different languages, we generally use JSON-formatted data when we interact with the front-end and back-end, and we use HTTP requests to fetch data from the backend, using some of the features of our KO, These ordinary data models must be converted to KO's monitoring properties, in turn, we use KO's monitoring properties, and sometimes need to convert these properties to normal JSON data to the background, then how to implement this transformation?
5.1. Convert JSON object to ViewModelFor example, we take a JSON object from the background and then turn it into our viewmodel and 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, take a JSON object, assign a value to Ojson, and then we convert the Ojson into ViewModel, the most intuitive way is to manually convert. For example, we can do this:
var Myviewmodeljson = { DeptName:ko.observable (), DeptLevel:ko.observable (), Deptdesc: Ko.observable () }; Ko.applybindings (Myviewmodeljson);
And 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); }
This enables the binding of JSON objects to viewmodel through manual binding. The advantage of this is flexibility, the downside is obvious, manual code is too large.
Fortunately, there is our omnipotent open source, always someone think of a better way, we use knockout. The mapping component is a good way to help us interface JSON objects to ViewModel transformations.
Knockout. Mapping open Source Address: Download
The following is a simple look at how it is used, or the above example, we do not have to implement any viewmodel definition, we need to refer to 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: This knock.mapping-lastest.js must be placed behind the knockout-3.4.0.min.js, otherwise it will not be called ko.mapping.
And then use it directly inside the success function.
Success:function (data, status) { var myViewModelJson2 = Ko.mapping.fromJS (data); Ko.applybindings (MyViewModelJson2); }
Let's look at the effect:
Code explanation: Through the AJAX request from the background to the JSON object, through the Ko.mapping.fromJS (), it is easy to convert it into a viewmodel, is not monkey sharp! Of course, in addition to this usage, you can also update existing ViewModel, 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, according to the value of data to update Myviewmodeljson this viewmodel.
5.2. Convert ViewModel to JSON objectIt says that the JSON object is converted to ViewModel, so what if we need to convert the ViewModel to a JSON object and pass it to the backend?
There are two methods available in knockout:
- Ko.tojs (): Convert ViewModel to JSON object
- Ko.tojson (): Converts the 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 ("Development Department"), DeptLevel:ko.observable ("2"), Deptdesc: Ko.observable ("Development Gang") }; Ko.applybindings (Myviewmodeljson);
So let's monitor the values of OJson1 and OJson2:
Code explanation: Through the above diagram, it is easy to understand the difference between the two methods, it is necessary to note that these two methods are KO, do not need the support of mapping components.
6. Create your own Data-bind property
It says so much, is introduced knockout inside of some bindings and monitoring, then, sometimes, we need to customize our data-bind, type such as: <label data-bind= "Mybind:name" ></ Label>, this requirement is particularly useful when it comes to component encapsulation, can it be implemented? Of course.
In Knockout, the Ko.bindinghandlers property is provided for customizing the Data-bind property, which has the following syntax:
Ko.bindingHandlers.MySelect = { init:function (element, Valueaccessor, Allbindingsaccessor, ViewModel) { }, update:function (element, Valueaccessor, Allbindingsaccessor, ViewModel) { }};
Just make a statement and then use the custom Data-bind in our HTML tag.
<div> <select data-bind= "myselect: $root" > <option id= "1" > Research and Development Department </option> < Option id= "2" > Personnel </option> <option id= "3" > Administrative department </option> </select> </div >
Myselect is our custom binding property, $root can be understood for the moment as initialization (although this is not strictly interpreted, if there is a more reasonable explanation, please correct it).
Code explanation: Through the above ko.bindinghandlers can be easily implemented custom binding properties, need to explain two points:
- Init, as the name implies, initializes the custom binding, which contains multiple parameters, typically with the first two parameters, the initial parameter represents the DOM element that initializes the custom binding, and the second parameter is typically used to pass the initialized parameter.
- Update, updates the callback and enters this method when the corresponding monitoring attribute changes. If a callback is not required, this method may not be declared.
In this case, the blogger combines a drop-down box component Mutiselect that was previously shared to simply illustrate the use of custom bindings.
6.1, the simplest mutiselectIn general, if we need to use KO to encapsulate some common components, we need to use our ko.bindinghandlers, the following blogger on the combination of Mutiselect components to say how to use.
First declare the custom ko.bindinghandlers, initialize our select tag inside the Init method
Ko.bindingHandlers.MySelect = { init:function (element, Valueaccessor, Allbindingsaccessor, ViewModel) { $ ( Element). MultiSelect (); }, update:function (element, Valueaccessor, Allbindingsaccessor, ViewModel) { } };
Then use it in the page tabs
<div style= "Text-align:center;" > <select data-bind= "myselect: $root" > <option id= "1" > Research and Development Department </option> <option Id= "2" > Personnel </option> <option id= "3" > Administrative department </option> </select> </div >
Finally, the third part, activating bindings
$ (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 puzzled, the third feeling does not have any practical significance. The blogger's understanding is that the DOM element needs to use Data-bind to bind the data, it must be enabled for KO's bindings, which is where the ko.applybindings ().
Get results:
6.2. Parameter PassingThe first step or custom ko.bindinghandlers
Ko.bindingHandlers.MySelect = { init:function (element, Valueaccessor, Allbindingsaccessor, ViewModel) { var Oparam = Valueaccessor (); $ (Element). MultiSelect (Oparam) , update:function (element, Valueaccessor, Allbindingsaccessor, ViewModel ) { }};
The second step is the same as above, using this custom binding in the HTML tag.
The third step is to pass in the parameter when the binding is activated
$ (function () { var multiselect = { enableclickableoptgroups:true,// the group onchange:function (option, Checked) { alert ("select Change"); } }; Ko.applybindings (MultiSelect);});
These three steps can be passed to the initialization of our Mutiselect:
Code Explanation: The second parameter of the Init event, we said, its main function is to get our ViewModel inside the parameters passed over, but here to use it as a method, why it is used, still needs to be researched!
Second, the first example of the increase and deletion check
At this point the foundation of the things finally is finished, originally intended to be a fix, can not expect the basis of things to expand so much space! Additions and deletions to the example of change to the next chapter. Welcome to learn to communicate, of course, also welcome recommendations !
Category: JS
Bootstraptable+knockoutjs implementation of adding and deleting solutions