1. Introduction:

Layui has been around for a couple of years, and the framework is perfect for our backend developers. Simple and easy to use, used more modules must be the table module and form module. However, in a development team, different people’s development level is different, if there is no unified public method, it will cause a lot of different styles and common bugs to appear in different pages, which will cost too much energy to modify the bug. So what we need to do is unify the style and method calls, and encapsulate the second time to make it easier for developers to call. On the other hand, it reduces the redundancy of the code.

2. Encapsulate layui-table

2.1. Page composition: Generally, the table composition on the page is as follows: search area header toolbar and table body [including processing of row and column events]

Options sets default values and can override default values, supports search methods (search/reset), and can retrieve layui’s table component

Externally provided methods

2.2. Parse each method from a use case

As shown below, the first step is to create the object (this is the table component object I encapsulated), the important thing is that the init method initializes the entire table

<script> var grid = new LayDataTable(); grid.init({ elem: '#listTable', data: resDt.data, // defaultToolbar: ['filter', 'print', 'exports', // { // title: 'wifi' // title //,layEvent: 'wifi' // event name, used for toolbar events //,icon: 'layui-icon-wifi' // icon class name //}, // {// title: 'License' // title //,layEvent: 'auz' // Event name, used for toolbar events //,icon: 'layui-icon-auz' // icon class name //} //], toolbar: Title: 'user table ', totalRow: true, // Enable cols: [ [ //... ] ] }, function(checkStatus, event) { console.log(checkStatus, event); }, function(obj) { console.log(obj); }, "searchId"); Function searchF() {grid.search(); function searchF() {grid.search(); Function reset() {grid.reset(); } </script>Copy the code

** init method **

The init method has four inputs: options for the table, click event for the header toolbar, click event for the table row, and the ID of the search area.

There are several things that need to be modified to match your project, mainly the parameters of the options of the table: parseData [because the key of the JSON returned by different backends is different, it needs to be assigned according to the fixed format of Layui] and request: By default, the paging parameter name is passed to the back end, and the sorting section, which listens to the sorting event, can also be channeled to the front end of the sorting field and how to pass parameters to the back end can be set according to the back end. This, like Request, is based on back-end configuration rather than layui format.

The reason for setting the search area ID is that initialization and subsequent searches require a uniform assembly of parameters. If this is also written every time, it would be exhausting to not encapsulate it, especially if the developer is determined to get input and select values one by one.

Reset method:

I’m using table rendering here, because I reset the checkboxes and the checkboxes and the multicheckboxes and the dropdowns are still the same and need to be rendered again. Only the controls in the search area are rendered to separate the areas.

When reset takes parameters, those parameters are injected into the search parameters. The parameter format is {}.

3. Complete JS:

var LayDataTable = (function() { var table; var l_options; var l_searchConfig; var currentTable; var $; var whereData={}; Var form; function init(_options, headEvenFun = null, rowEvenFun = null, searchConfig = {}) { var _this = this; / / set the default item _options. Elem = _options. Elem | | ""; _options.height = _options.height || 700; // Default paging configuration if (typeof(_options.page)! = "boolean") { _options.page = _options.page ||{}; _options.page = object. assign({first: 'home ', prev:' previous ', next: 'next ', last:' last ', groups: '6', layout: ['count', 'first', 'prev', 'page', 'next', 'limit', 'refresh', 'skip'], theme: '#fe0627' },_options.page); } var options = Object.assign({ title: '', defaultToolbar: ['filter', 'print'], limits: [10, 50, 100], limit: Even: typeof(_options.even)==' Boolean '? _options.even:true, // enable interlacing background size: 'lg', // small size table text:{none: 'no data yet' // default: no data. ParseData :function(res) {parseData:function(res) {parseData:function(res) {return { Res. status, // parse the interface status "MSG ": res.message, // parse the message text "count": res.total, // parse the data length "data": res.data.item // parse the data list}; }, request:{pageName: 'start', // Page parameter name, default: page limitName: 'length' // Parameter name of the amount of data per page, default: limit}},_options); var elemDom = document.getElementById(options.elem.substr(1)); var tableFilter = elemDom.getAttribute("lay-filter"); l_options = options; If (searchConfig) {l_searchConfig =searchConfig; } layui.use(['table', 'jquery','form'], function() { table = layui.table; $ =layui.$; setParams(); l_options.where = whereData; CurrentTable = table.render(options); // First instance currentTable = table.render(options); form= layui.form; If (Typeof (headEvenFun) == "function") {table.on('toolbar(' + tableFilter + ')', function(obj) { headEvenFun(table.checkStatus(obj.config.id), obj.event); }); } if (typeof(rowEvenFun) == "function") {table.on('tool(' + tableFilter + ')', function(obj) { rowEvenFun(obj); }); } / / monitor sorting event table. On (' sort (' + l_options. Elem. Replace (" # ", "") + ') ', function (obj) {/ / note: Table.reload (l_options.elem. Replace ("#","")), {initSort: Obj // Records the initial sort, if not set, will not mark the sort state of the table header. Field: obj. Field // order: obj. Type // sort}}); }); }); } function search() {setParams(); l_options.where = whereData; currentTable.reload(l_options); } function getTable() {// getTable return table; } function setParams(){var type; var searchId = typeof(l_searchConfig)==='object'? l_searchConfig.searchId:l_searchConfig; $("#"+searchId+" input,#"+searchId+" select").each(function(ind, item) { type = $(item).attr("type"); if ($(item).attr("name")) { if (type == 'radio' || type == 'checkbox') { whereData[$(item).attr("name")] = $("input[name='" + $(item).attr("name") + "']:checked").val() || ''; } else { whereData[$(item).attr("name")] = $(item).val() || ''; }}})} function reset(whereParams) {// reset search var type; whereData = {}; l_options.where={}; var searchId = typeof(l_searchConfig)==='object'? l_searchConfig.searchId:l_searchConfig; $("#"+searchId+" input,#"+searchId+" select").each(function(ind, item) { type = $(item).attr("type"); if ($(item).attr("name")) { if (type == 'hidden') { whereData[$(item).attr("name")] = $(item).val() || ''; } else if (type == 'radio' || type == 'checkbox') { $(item).attr("checked", false); whereData[$(item).attr("name")] = ''; } else { whereData[$(item).attr("name")] = ''; $(item).val(""); }}}); Object.assign(whereData,whereParams||{}) ; // Partially refresh the top div class="layui-form" // lay-filter must be set to the same value as searchId in seachConfig form.render('select',searchId); form.render('radio',searchId); form.render('checkbox',searchId); CurrentTable. Reload ({where: whereData, page:{curr: 1// restart from page 1}}); } return function() {this.init = init; this.search = search; // Search this.reset = reset; // Reset search this.gettable = getTable; }}) (); // Properties give you the ability to add properties and methods to objects. Laydatatable. prototype = {}Copy the code

The source code

This article is from: Programmer Ken, exclusive platform CSDN, SegmentFault, Jianshu, Open Source China (OSChina), Nuggets, reprint please indicate the source.