Este artículo será interesante para aquellos que están acostumbrados a resolver problemas complejos con métodos simples. A primera vista, trabajar con big data puede parecer una tarea abrumadora. Pero si posee herramientas especializadas, organizar y mostrar grandes conjuntos de datos le parecerá poco más que un entretenimiento divertido. Hoy hablaremos de una de las herramientas más extraordinarias para trabajar con datos proporcionados por el equipo de Webix. Hablaremos de un widget tan simple y al mismo tiempo complejo de la biblioteca de IU de Webix como DataTable. Averigüemos cuál es su fuerza.
Biblioteca Webix y widget DataTable
Webix UI — JavaScript , ui . , . , . , , , . , .
DataTable - Webix. . (XML, JSON, CSV, JSArray, HTML tables) . " ". , . , , . , 1 000 000 , . , .
, DataTable API , , , , , . DataTable .
Webix , . , . . " Booking Webix UI".
Webix , index.html. , 2 : Pro-. , Pro-. Pro-, DataTable. CDN :
<script type="text/javascript" src="//cdn.webix.com/pro/edge/webix.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.webix.com/pro/edge/webix.css">
index.html . :
<!DOCTYPE html>
<html>
<head>
<title>Webix Booking</title>
<meta charset="utf-8">
<!--Webix sources -->
<script type="text/javascript" src="//cdn.webix.com/pro/edge/webix.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.webix.com/pro/edge/webix.css">
</head>
<body>
<script type="text/javascript">
//...
</script>
</body>
</html>
<script>...</script>, .
webix.ui(). , HTML . webix.ready(function(){}). :
webix.ready(function(){
webix.ui({
/* */
});
});
index.html . DataTable.
, “” , . datatable.js :
const datatable = {
view:"datatable",
autoConfig:true,
url:"./data/data.json"
}
DataTable view:"datatable". url , . , JSON. (xml, jsarray csv), datatype. , , data parse().
autoConfig, . . .
, . , datatable, index.html.
DataTable index.html:
<!--App sources -->
<script src="js/datatable.js" type="text/javascript" charset="utf-8"></script>
, :
<script type="text/javascript">
webix.ready(function(){
webix.ui( datatable );
});
</script>
:
, 3 , . , . , . . .
, . columns:[ ]. . , .
, id. , (). “” header.
. width, minWidth, maxWidth fillspace. , , fillspace . :
{
view:"datatable",
columns:[
{ id:"rank", header:"Rank", width:45 },
//...
{ id:"vin_code", header:"VIN", minWidth:50, width:180, maxWidth:300 },
//...
{ id:"address", header:"Address", minWidth:200, fillspace:true },
//...
],
url:"./data/data.json"
}
:
, , header.
, . autowidth, , columnWidth, . 100px.
. resizeColumn true, , css:"webix_data_border webix_header_border".
, . scroll, false. “xy”.
, , .
, , id . . template , . , . , #data_key#. , .
, . , ? , . -. :
{
view:"datatable",
id:"car_rental_table",
//...
columns:[
{ id:"stared", header:"",
template:function(obj){
return `<span class='webix_icon star mdi mdi-"+(obj.star ? "star" : "star-outline") + "'></span>`;
}, ...,
},
//...
]
}
template , span . “star” “star-outline” . , :
function selectStar(id){
const table = $$("car_rental_table");
const item = table.getItem(id);
const star = item.star?0:1;
item.star = star;
}
id . $$("car_rental_table") id. getItem(), id , . star 0 ( ) 1 ( ).
, . css , onClick:
//...
url:"./data/data.json",
onClick:{
"star":(e,id) => selectStar(id)
},
//...
. :
“Available”. true false, . , “Yes” “No”.
, . :
function customCheckbox(obj, common, value){
if(value){
return "<span class='webix_table_checkbox checked'> YES </span>";
}else{
return "<span class='webix_table_checkbox notchecked'> NO </span>";
}
}
“Available”:
columns:[
//...
{ id:"active", header:"Available", template:customCheckbox, ...,},
]
:
. , , . leftSplit ( 3). .
“Color”. HEX , . . . . :
columns:[
//...
{ id:"color", header:"Color", template:`<span style="background-color:#color#;
border-radius:4px; padding-right:10px;"> </span> #color#`},
//...
]
, ( ) HEX .
:
, id . , . , .
, "ar make", . 1 24 "car_make":
//data.json
[
{ "id":1, "rank":1, "car_make":22, ..., "country":1, "company":1, ..., },
{ "id":2, "rank":2, "car_make":10, ..., "country":2, "company":3, ..., },
{ "id":3, "rank":3, "car_make":16, ..., "country":1, "company":2, ..., },
//...
]
, , . :
//car_make.json
[
{ "id":22, "value":"Toyota" }, ...,
{ "id":10, "value":"GMC" }, ...,
{ "id":16, "value":"Mazda" }, ...,
//...
]
collection ():
columns:[
//...
{ id:"car_make", header:"Car make", collection:"./data/car_make.json", ...,},
//...
]
, , “Car make” . “Company”, “Country” “Card”.
:
, . , format. . . :
columns:[
//...
{ id:"date", header:"Date", format:webix.i18n.longDateFormatStr, ..., },
{ id:"price", header:"Price", format:webix.i18n.priceFormat, ..., },
//...
]
“05/26/2021”. “26 May 2021”. webix.i18n.longDateFormatStr, “Date”, Date . “05/26/2021”, . Date .
scheme. webix.i18n.dateFormatDate. :
{
view:"datatable",
//...
scheme:{
$init:function(obj){
obj.date = webix.i18n.dateFormatDate(obj.date)
}
},
columns:[...]
}
. "Price". . webix.i18n.priceFormat ( 199) : “$199”. .
:
. , .
DataTable sort. . , , :
"int" -
"date" -
"string" - ,
"text"- , ( )
columns:[ { id:"car_model", header:"Model", width:120, ..., sort:"string", }, ..., { id:"car_year", header:"Year", width:85, ..., sort:"int" }, ..., { id:"country", header:"Country", width:140, ..., sort:"text" }, ..., { id:"date", header:"Date", width:150, ..., sort:"date" }, ..., ]
. , , . sort "multi" . , Ctrl/Command .
( ), sort.
. Webix. content, . .
, . selectFilter “Company”. collection, . . :
columns:[
//...
{
id:"company",
header:["Company",{content:"selectFilter"}],
collection:"./data/company.json", ...,
}, ...,
]
:
“Car make” textFilter. . . , , . , , . , . :
columns:[
//...
{ id:"car_make", header:["Car make", {
content:"textFilter", placeholder:"Type car make",
compare:function(item, value, data){
const colValue = cars_make_data.getItem(item).value;
const toFilter = colValue.toLowerCase();
value = value.toString().toLowerCase();
return toFilter.indexOf(value) !== -1;
} }], collection:cars_make_data, ...,
},
//...
]
“Model”. , :
columns:[
//...
{ id:"car_model", header:["Model", {content:"textFilter", placeholder:"Type model"}, ...,],
//...
]
:
“Year”, . excelFilter. , , . :
columns:[
//...
{ id:"car_year", header:[{text:"Year", content:"excelFilter", mode:"number"}], ...,},
//...
]
mode , . , , . :
, . datepickerFilter. . :
columns:[
//...
{ id:"date", header:["Date", {content:"datepickerFilter"}], ..., },
//...
]
:
. , editable true . , . , . (“dblclick”) (“custom”).
, . , .
text. , . . : editor . :
{
view:"datatable",
//...
editable:true,
editaction:"dblclick",
columns:[
{ id:"rank", header:"Rank", editor:"text", ..., },
{ id:"car_model", header:"Model", editor:"text", ..., },
{ id:"manager", header:"Manager", editor:"text", ..., },
//...
],
//...
}
, :
, . popup. . 250px 50px . “Address”:
columns:[
{ id:"address", header:"Address", editor:"popup", ...,},
//...
],//...
“Address”, :
c “Available”. , , true false YES NO. , . inline-checkbox. . checkboxRefresh true. , checkbox- . :
{
//...
checkboxRefresh:true
columns:[
//...
{ id:"active", header:"Available", editor:"inline-checkbox", template:customCheckbox, ..., },
//...
],
//...
}
, .
, . combo. . . :
columns:[
{ id:"company", header:"Company", editor:"combo",
collection:"./data/company.json", ..., },
{ id:"car_make", header:"Car make", editor:"combo",
collection:cars_make_data, ..., },
{ id:"country", header:"Country", editor:"combo",
collection:"./data/country.json", ..., },
//...
],
//...
, :
“Color”. , HEX . Webix , , . color. :
columns:[
{ id:"color", header:"Color", editor:"color", template:..., },
//...
],
//...
“Color”, :
“Date”. date. , , , . :
columns:[
{
id:"date", header:"Date", editor:"date",
format:webix.i18n.longDateFormatStr, ...,
},
//...
],
//...
“Date”, :
, . . ? . Webix , . , .
, webix.rules.isNumber. , .
, . webix.rules.isEmai.
. , 20 500 . :
function(obj){ return (obj>20 && obj<500) }
webix.rules.isNotEmpty. , .
, rules. id . :
column:[...],
rules:{
rank:webix.rules.isNumber,
company:webix.rules.isNotEmpty,
email:webix.rules.isEmail,
price:function(obj){ return(obj>20 && obj<500) },
//
}
, . , , :
, , . . DataTable colspan rowspan, HTML . , Price, Card IBAN Payment information. header :
column:[
//...
{ id:"price", header:[{text:"Payment information", colspan:3}, "Price"], ..., },
{ id:"credit_card", header:["","Card"], ..., },
{ id:"iban", header:["","IBAN"], ..., },
//...
]
:
, . footer true . colspan. “Available”, , . :
column:[
//...
{ id:"stared", header:[...], ..., footer:{ text:"Available:", colspan:2 } },
//...
{ id:"active", header:[...], ..., footer:{content:"summColumn"}, ..., },
//...
]
, {content:"summColumn"} , true . “Available” . :
, . Webix headerMenu. . , .
headerMenu . :
//...
headermenu:{
width:210,
data:[
{ id:"car_year", value:"Year" },
{ id:"color", value:"Color" },
{ id:"vin_code", value:"VIN" },
{ id:"phone_number", value:"Phone" },
//...
]
},
column:[
{ id:"stared", header:[{ content:"headerMenu", colspan:2, ...,}], ..., },
{ id:"rank", header:["",""], ..., },
//...
]
headermenu , .
:
. , .
, . . , DataTable .
, pager.js. :
//pager.js
const pager = {
view:"pager",
id:"pager",
size:20,
group:5,
template:`{common.first()} {common.prev()}
{common.pages()} {common.next()} {common.last()}`
};
size group (20) (5). , , . template, ( ).
index.html :
//index.html
<!--App sources -->
<script src="js/datatable.js" type="text/javascript" charset="utf-8"></script>
<script src="js/pager.js" type="text/javascript" charset="utf-8"></script>
//...
<script type="text/javascript">
webix.ready(function(){
webix.ui({
rows:[
datatable,
{cols:[
{},pager,{}
]}
]
});
});
</script>
, , , ( 20 ). pager id . Webix. :
, . , . .
, Webix . (<span class='webix_icon wxi-drag'></span>), (common.trashIcon()).
, columns :
column:[
//...
{
header:[{text:"<span class='webix_icon wxi-plus-circle'></span>", colspan:2}],
width:50, template:"<span class='webix_icon wxi-drag'></span>"
},
{ header:["",""], width:50, template:"{common.trashIcon()}" }
]
2 , . , , , 2 , . , rightSplit 2. :
. . css , onClick. . , wxi-plus-circle wxi-trash:
onClick:{
"wxi-plus-circle":() => addNewElement(), //
"wxi-trash":(e,id) => removeElement(id), //
//...,
}
. :
function addNewElement(){
const table = $$("car_rental_table"); //
//
const id_new_elem = table.add({"active":0,"color":"#1c1919","date":new Date()});
table.showItem(id_new_elem); //
}
add() . id , showItem(), () .
:
function removeElement(id){
$$("car_rental_table").remove(id);
}
remove() id .
. drag. “order”. , ( ) .
. wxi-drag .
on, onBeforeDrag:
on:{
onBeforeDrag:function(data, e){
return (e.target||e.srcElement).className == "webix_icon wxi-drag";
}
}
:
, .
, Excel. , .
toolbar.js toolbar, Reset filters, Add column Export to Excel. :
const toolbar = {
view:"toolbar",
css:"webix_dark",
height:50,
//...
cols:[
//...
{ view:"button", label:"Reset filters", click:resetFilters },
{ view:"button", label:"Add column", click:addColumn },
{ view:"button", label:"Export to Excel", click:exportToExcel }
]
};
click . . , . :
function resetFilters(){
const table = $$("car_rental_table");
table.filter();
table.showItem(table.getFirstId());
table.setState({filter:{}});
}
filter(), , . setState() .
, . :
function addColumn(){
const table = $$("car_rental_table");
table.config.columns.splice(3,0,{
id:"c"+webix.uid(),
header:`<span class="webix_icon wxi-close-circle"
webix_tooltip="Delete column"></span>Extra column`,
editor:"text",
width:120
});
table.refreshColumns();
}
config.columns 4 . js splice(). , refreshColumns().
, Excel. :
function exportToExcel(){
webix.toExcel("car_rental_table", {
filename:"Car Rental Table",
filterHTML:true,
styles:true
});
}
webix.toExcel(), id . .
, toolbar.js index.html toolbar :
webix.ui({ rows:[ toolbar, datatable, {cols:[ {},pager,{} ]} ] });
:
, , Excel.
. , wxi-close-circle. , . onClick:
onClick:{
//...
"wxi-close-circle":(e,id) => deleteColumn(id)
}
:
function deleteColumn(id){
const table = $$("car_rental_table");
table.clearSelection();
table.editStop();
table.refreshColumns(table.config.columns.filter(i=>i.id !== id.column));
}
config.columns , refreshColumns().
:
, , .
El código de la aplicación terminada se puede encontrar aquí .
En este artículo, hemos detallado cómo crear una aplicación basada en el widget DataTable de la biblioteca de la interfaz de usuario de Webix, y también hemos aprendido cómo personalizar la tabla usando una amplia variedad de propiedades y métodos. Como puede ver, todas las configuraciones son intuitivas y fáciles de usar. De hecho, esto es solo una pequeña parte de todo lo que la mesa Webix tiene para ofrecernos. Para obtener información más detallada, puede ir a la documentación , donde puede encontrar una descripción detallada de todas las capacidades del componente con ejemplos ilustrativos.