Home > Web Front-end > JS Tutorial > body text

Combining BootstrapTable with KnockoutJS to implement addition, deletion, modification and query functions [1]_javascript skills

PHP中文网
Release: 2019-07-11 11:33:02
Original
3957 people have browsed it

bootstrap is a front-end framework that liberates good things for web developers. the ui it presents is very high-end and classy. in theory, there is no need to write a line of css. just add the appropriate attributes to the tag.

knockoutjs is an mvvm framework implemented in javascript. very cool. for example, after the list data items are added or deleted, there is no need to refresh the entire control fragment or write js to add or delete nodes by yourself. you only need to pre-define the template and attributes that conform to its syntax definition. simply put, we only need to focus on data access.

1. introduction to knockout.js

1. knockout.js and mvvm

nowadays, various front-end frameworks are overwhelming and dazzling. don’t lament that being a programmer is really hard. there are always endless techniques to learn, and when will it be the end, unless you transform! the sea of ​​suffering is boundless, it’s up to you to decide whether you want to turn back or go to the shore!

knockout.js is a lightweight front-end framework based on the mvvm pattern. how lightweight is it? according to the latest version v3.4.0 shown on the official website, it is only 22kb. it can handle the binding of data model and interface dom in a friendly manner. the most important thing is that its binding is two-way. that is to say, if the data model changes, the data on the interface dom will also change accordingly. in turn, the interface dom will change accordingly. if the data on the database changes, the data model will also respond to this change. this can greatly reduce the amount of our front-end code and make our interface easy to maintain. we no longer need to write a lot of event monitoring data models and interface dom changes. the blogger below will illustrate these two points based on a usage example.

knockout.js official website: http://knockoutjs.com

knockout.js open source address: https://github.com/knockout/knockout

mvvm pattern: this is a design pattern for creating user interfaces. mvvm splits it into three parts: model, view, and viewmodel. model is the data model, view is our view, and viewmodel is a view model. used to bind the data model and dom elements on the view. if you have used wpf and silverlight, understanding this shouldn't be a problem; if you haven't, it doesn't matter. after reading this article, you will have a general understanding.

2. the simplest example

generally speaking, if you start using knockout.js from scratch, you need to do at least the following four steps

2.1. go to the official website to download the knockout.js file, and then quote it go to the view page.

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

note: knockout.js does not require the support of jquery. if your project needs to use jquery related operations, please quote jquery; otherwise just reference the above files.

2.2. definition of viewmodel

what is viewmodel? in fact, in js, it looks like a json object. we define a viewmodel:

var myviewmodel = {
name: "lilei",
profession: "软件工程师",
};
Copy after login

2.3, define the label binding data-bind in the view view

<div> 
姓名:<label data-bind="text:name"></label><br />
职业:<input type="text" data-bind="textinput:profession" />
</div>
Copy after login

note: the text corresponding to the input tag needs to use textinput, while the text of the ordinary tag can be text.

2.4. activate binding

after completing the above three steps, you also need to activate the knockout binding

ko.applybindings(myviewmodel);
Copy after login

by doing these four steps, the simplest viewmodel data binding is basically realized.

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. what is the second one? from ko.applybindings(myviewmodel); we can see that the second parameter is an optional parameter, which represents the scope of the label bound to the viewmodel. for example, let's change the above code:

<div> 
姓名:<label id="lb_name" data-bind="text:name"></label><br />
职业:<input type="text" data-bind="textinput:profession" />
</div> 
ko.applybindings(myviewmodel,document.getelementbyid("lb_name"));
Copy after login

it can be seen that the second parameter limits the scope of myviewmodel, that is to say, it will only take effect if it is bound to the label with id="lb_name". the second parameter is a container tag such as a div, which indicates that the scope of the binding is all sub-tags under the div.

3. monitoring attributes

up to the above four steps , we can't see any effect, all we see is binding the data of a json object to the html tag. what's the point of doing this? doesn't it complicate a simple problem? don't worry, witness the miracle now! as mentioned above, the most important significance of knockout is two-way binding, so how to achieve our two-way binding? the answer is monitoring properties.

in knockout, there are three core monitoring attributes: observables, dependentobservables, and observablearray. the meaning of observe is translated as observation. it doesn’t feel right to call it observation attribute or observation attribute. it’s so appropriate, let’s call it monitoring attribute for now.

3.1. observables: monitoring properties

we change the above example to this:
p>



index3

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


<div> 
姓名:<label data-bind="text:name"></label><br />
职业:<input type="text" data-bind="textinput:profession" />
</div>
//1.定义viewmodel var myviewmodel = { name: ko.observable("lilei"), profession: "软件工程师", }; //2.激活绑定 ko.applybindings(myviewmodel); $(function () { //注册文本框的textchange事件 $("#txt_testobservable").on("input", function () { myviewmodel.name($(this).val()); }); });
Copy after login

ko.observable("lilei") the meaning of this sentence is to add the name attribute of the viewmodel as a monitoring attribute. when the name attribute becomes a monitoring attribute, something magical will happen. let's take a look when we write myviewmodel. when:

name changes from the original attribute to a method. that is to say, once ko.observable() is added, the corresponding attribute will become a method. , then the value acquisition and assignment of name need to be processed using myviewmodel.name().

code explanation: obviously myviewmodel.name($(this).val()); this sentence assigns the value of the current text box to the name attribute, because the interface is bound to the name attribute, so the value in the label also changes accordingly. or you may say that this can also be done using the textchange event. as long as the value of the current text box is assigned to the label label, this effect can also be achieved. this is nothing. indeed, your way of writing can achieve the goal, but the significance of our monitoring attributes is that if the value of name is changed anywhere, the interface will change accordingly. instead of assigning values ​​to label tags everywhere, js only needs to pay attention to just click on the method myviewmodel.name(). isn’t it awesome~~

3.2. dependentobservables: monitoring dependency attributes

if you haven’t enjoyed reading the above monitoring attributes? let's take a look at the use of monitoring dependency attributes.

let’s change the code and take a look:



index3

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


  姓名: 职业: 描述:
//1.定义viewmodel var myviewmodel = { name: ko.observable("lilei"), profession: ko.observable("软件工程师"), }; myviewmodel.des = ko.dependentobservable(function () { return "本人姓名——" + myviewmodel.name() + ",职业——" + myviewmodel.profession(); }); //2.激活绑定 ko.applybindings(myviewmodel);
Copy after login

code explanation: by adding monitoring dependent attribute ko.dependentobservable() can monitor the value of the des attribute to changes in both name and profession at the same time. if any one of them changes, the label bound to des will trigger the change. the biggest advantage of this is that it avoids the need for our js to go the trouble of operating dom is a bit interesting.

3.3. observablearray; monitoring array

in addition to the above two, ko also supports monitoring of array objects. let’s take a look at an example:



index3

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


var deptarr = ko.observablearray([ { id: 1, name: '研发部' }, { id: 2, name: '行政部' }, { id: 3, name: '人事部' } ]); var viewmodel = { deptarr: deptarr, }; ko.applybindings(viewmodel); var i=4; $(function () { $("#btn_test").on("click", function () { deptarr.push({ id: i++, name: $("#txt_testobservable").val() }); }); });
Copy after login

code explanation: the above is through ko.observablearray() the method adds monitoring of the array object, that is to say, as long as the array change is made to the deptarr array object anywhere in js, the ui will be triggered to give a corresponding response. one thing to note is that the monitored array is actually the monitored array object itself. changes in the properties of the sub-objects in the array object cannot be monitored. for example, we change the click event to this:

$(function () {
$("#btn_test").on("click", function () {
deptarr[1].name = "aaa";
});
});
Copy after login

this shows that array monitoring actually monitors the array object itself, and does not monitor attribute changes of elements in the array. if you really need to monitor the attribute changes of the objects in the data, you need to use ko.observable() on the object attributes in the data, and use the two together. those who are interested can try it.

4. common data-bind attributes in ko

above, we used multiple data-bind attributes, so how many such data-bind attributes are there in knockout. here we list some commonly used properties.

4.1, text and inputtext

text, as the name suggests, means text. this binding attribute is generally used for

and other tags display text. of course, any tag can use this binding if you wish. it's using basically nothing to say. if ko.observable() is not used, it is static binding, otherwise it is dynamic binding.

inputtext, the text of the input tag, is equivalent to the value attribute of the input tag.

  <div> 
姓名:<label data-bind="text:name"></label><br />
职业:<input type="text" data-bind="textinput:profession" />
</div> 
     //1.定义viewmodel
var myviewmodel = {
name: ko.observable("lilei"),
profession: "软件工程师",
};
//2.激活绑定
ko.applybindings(myviewmodel);
Copy after login

4.2, value

this binding attribute is generally used for input tags, and is basically similar to the inputtext above. it's just that value is more standardized.

there is also a parameter valueupdate used together with value, which indicates that the value is updated when the interface performs an operation. the main values ​​of valueupdate include change/keyup/keypress/afterkeydown, etc. respectively represent text changes, keyboard shrinkage, keyboard press, keyboard press and other operations to update the value of the viewmodel corresponding to value.

姓名:
<input type="text" data-bind="value:name,valueupdate:'keyup'" /><br /> 
    var myviewmodel = {
name: ko.observable("lilei"),
};//2.激活绑定
ko.applybindings(myviewmodel);
Copy after login

the above code indicates that the value attribute of the text box and the name attribute of myviewmodel are updated when the keyboard is retracted.

4.3. checked

checked binding is generally used for checkbox, radio and other form elements that can be selected. it corresponds to the value is of bool type. the usage is basically similar to value, so i won’t repeat the explanation.

4.4. enable

enable binding is generally used to enable label elements, and is generally used to enable form elements. and disabled. contrary to disabled, the corresponding value is also of type bool.

<div>
<input type="text" data-bind="enable:ismen"/>
</div>
<script type="text/javascript">
//1.定义viewmodel
var myviewmodel = {
name: ko.observable("lilei"),
profession: ko.observable("软件工程师"),
age: ko.observable(40),
ismen:ko.observable(true)
};
//2.激活绑定
ko.applybindings(myviewmodel);
myviewmodel.ismen(false);
</script>
Copy after login

because the ismen property becomes false, all corresponding text boxes will appear disabled.

4.5. disabled

is the opposite of enabled, and its usage is similar to enable.

4.6, options

in the above, options were used when using select binding, which represents the select tag. a collection of options, the corresponding value is an array, indicating the data source of this drop-down box. monitoring of this data source can be enabled using observablearray. see above for usage.

4.7, html

text binding is actually the setting and value of the innertext tag, so the same goes for , html binding is also the setting and value of innerhtml. its corresponding value is an html tag.

4.8, css

css binding is to add or delete one or more styles (classes) to dom elements superior. use the 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("软件工程师"),
age:ko.observable(40)
};
Copy after login

the div will display the background color.

if you need to add or remove multiple styles, just make slight changes, such as:

<div data-bind="css:{testbold:myviewmodel.name()=='lilei',testborder:myviewmodel.profession()=='php工程师'}">aaaa</div>
Copy after login

4.9, style

if the function of css binding is to dynamically add or remove class styles to tags, then the function of style binding is to tags dynamically add or remove a style. for example:

<div data-bind="css:{background-color:myviewmodel.name()=='lilei'?'red':'white'}">aaaa</div>
Copy after login

if you are adding or removing multiple ones, use the same css binding method

4.10, attr

attr binding is mainly used to add and remove one or more attributes (including custom attributes) to tags, yonghe and css similar.

4.11. click

click binding means adding the execution method of the click event on the corresponding dom element. can be used on any element.

<div>
<input type="button" value="测试click绑定" data-bind="click:clickfunc" />
</div> 
    var myviewmodel = {
clickfunc:function(){
alert($(event.currenttarget).val());
}
};
ko.applybindings(myviewmodel);
Copy after login

event.currenttarget represents the currently clicked dom element. sometimes for simplicity, we directly use anonymous functions to bind, such as:

<div>
<input type="button" value="测试click绑定" data-bind="click:function(){
alert('点击了');
}" />
</div>
Copy after login

however, this way of writing js into html is difficult for bloggers to accept, and they find it relatively inconvenient to maintain, especially when the logic in the click event is slightly complicated. therefore, it is not recommended to write this anonymous function directly unless necessary.

4.12, others

for all bindings of data-bind, you can see the introduction on the official website, here not listed one by one. when you need to use it, just check it on the official website. take a look at all the bindings listed on the official website

5. conversion and conversion of json objects and monitoring attributes relationship

we know that in order to avoid direct presentation in different languages, we generally use json format data when interacting with the front end and back end. we retrieve it from the back end through http requests. to use some of the features of our ko, we must convert these ordinary data models into ko's monitoring attributes; in turn, when we use ko's monitoring attributes, sometimes we need to convert these attributes into ordinary the json data is transferred to the background, so how to achieve this conversion?

5.1. convert json object into viewmodel

for example, we get a json object from the background and then change it into into our viewmodel, and then bound to our interface dom.

$.ajax({
url: "/home/getdata",
type: "get",
data: {},
success: function (data, status) {
var ojson = data;
}
});
Copy after login

we send a request to the backend, get a json object, assign it to ojson, and then we convert ojson into viewmodel, the most intuitive way is to convert manually. for example, we can do this:

    var myviewmodeljson = {
deptname: ko.observable(),
deptlevel: ko.observable(),
deptdesc:ko.observable()
};
ko.applybindings(myviewmodeljson);
Copy after login

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);
}
Copy after login

in this way, through manual binding, the binding of the json object to the viewmodel is achieved. the advantage of this is flexibility, but the disadvantage is obvious that the amount of manual code is too large.

fortunately, with our omnipotent open source, someone will always come up with a better way. we can use the knockout.mapping component to help us convert the interface json object to the viewmodel.

knockout.mapping open source address: download

let’s take a brief look at how to use it. it’s still the above example. we don’t need to implement any viewmodel definition. first you need to reference knockout.mapping.js

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

note: here knockout.mapping-lastest.js must be placed in knockout-3.4. 0.min.js, otherwise ko.mapping cannot be called.

then use it directly in the success function

         success: function (data, status) {
var myviewmodeljson2 = ko.mapping.fromjs(data);
ko.applybindings(myviewmodeljson2);
}
Copy after login

code explanation: request from the json object obtained in the background can be easily converted into a viewmodel through ko.mapping.fromjs(). isn’t it sharp! of course, in addition to this usage, you can also update the existing viewmodel as follows:

    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)
}
});
});
Copy after login

in success, update the myviewmodeljson viewmodel according to the value of data.

5.2. convert viewmodel into json object

the above said that json object is converted into viewmodel, then conversely, if we need to convert the viewmodel into a json object and pass it to the backend. what should we do?

knockout provides two methods:

•ko.tojs( ): convert the viewmodel to a json object
•ko.tojson(): convert 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("研发部"),
deptlevel: ko.observable("2"),
deptdesc: ko.observable("开发一伙人")
};
ko.applybindings(myviewmodeljson);
Copy after login

then let’s monitor the values ​​of ojson1 and ojson2

code explanation: what needs to be explained here is that these two methods come with ko and do not require the support of the mapping component.

6. create your own data-bind attribute

above having said so much, they all introduce some binding and monitoring in knockout. so, sometimes, we need to customize our data-bind, such as: , this this kind of requirement is especially useful when encapsulating components. can it be realized? sure.

in knockout, the ko.bindinghandlers attribute is provided for customizing the data-bind attribute. its syntax is as follows:

ko.bindinghandlers.myselect = {
init: function (element, valueaccessor, allbindingsaccessor, viewmodel) {
},
update: function (element, valueaccessor, allbindingsaccessor, viewmodel) {
}
};
Copy after login

just declare it like this, and then you can use custom data-bind in our html tag.

<div> 
<select data-bind="myselect:$root">
<option id="1">研发部</option>
<option id="2">人事部</option>
<option id="3">行政部</option>
</select>
</div>
Copy after login

myselect is our custom binding property, and $root can be understood as initialization for the time being (although this explanation is not rigorous, if if there is a more reasonable explanation, please correct me).

code explanation: custom binding attributes can be easily implemented through the above ko.bindinghandlers. two points need to be explained:

•init, as the name suggests, initializes custom binding defined, it contains multiple parameters, the first two parameters are generally used more often, the first parameter represents the initialization of the custom bound dom element, and the second parameter is generally used to pass the initialization parameters.
•update, update callback, will enter this method when the corresponding monitoring attribute changes. if no callback is required, this method can be left undeclared.

here, the blogger will briefly explain the use of custom binding based on the previously shared drop-down box component mutiselect.

6.1. the simplest mutiselect

generally, if we need to use ko to encapsulate some common components, we need to use our ko.bindinghandlers. the following blogger will explain how to use it in conjunction with 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) {
}
};
Copy after login

then use

<div style="text-align:center;"> 
<select data-bind="myselect:$root">
<option id="1">研发部</option>
<option id="2">人事部</option>
<option id="3">行政部</option>
</select>
</div>
Copy after login

the last third part, activate binding

$(function () {
var multiselect = {};
ko.applybindings(multiselect);
});
Copy after login

if you do not need to pass parameters, you only need to bind an empty viewmodel here. some people are confused, the third part seems to have no practical significance. the blogger's understanding is that dom elements need to use data-bind to bind data, and ko binding must be enabled, which is ko.applybindings() here.

the first step is to customize ko.bindinghandlers

ko.bindinghandlers.myselect = {
init: function (element, valueaccessor, allbindingsaccessor, viewmodel) {
var oparam = valueaccessor();
$(element).multiselect(oparam);
},
update: function (element, valueaccessor, allbindingsaccessor, viewmodel) {
}
};
Copy after login

the second step is the same as above, in the html tag this custom binding is used inside.

the third step is to pass in the parameters when activating the binding

$(function () {
var MultiSelect = {
enableClickableOptGroups: true,//收起分组
onChange: function (option, checked) {
alert("选择改变");
}
};
ko.applyBindings(MultiSelect);
});
Copy after login

through this three steps can pass the parameters to the initialization of our mutiselect:

code explanation: the second parameter of the init event, we said, its main function is to obtain the parameters passed in our viewmodel, but it is used as a method here. why it is used in this way remains to be studied!

2. the first example of adding, deleting, modifying and checking

so far the basics are finally laid out. i originally planned to finish it in one article, but i didn’t expect that the basics would be spread out in so many pages! the example of adding, deleting, modifying and checking will be placed in the next article. bootstraptable is combined with knockoutjs to implement the adding, deleting, modifying and checking functions [2]. learning and exchange are welcome, and of course recommendations are welcome!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template