Home >Web Front-end >JS Tutorial >Detailed explanation of CascadeView cascade component implementation ideas (separation ideas and singly linked lists)_javascript skills
This article introduces the implementation idea of a similar cascading function that I recently did for provinces and cities. In order to achieve the separation of responsibilities and performance and behavior as much as possible, this function was split into two components and a single linked list was used. To implement the key cascading logic, the next paragraph has a gif of demonstration effect. Although this is a very common function, the implementation logic of this article is clear and the code is easy to understand. It breaks away from the semantics of provincial and municipal cascades and considers the separation of performance and behavior. I hope the content of this article can bring some reference for your work. value, welcome to read and correct.
Cascade cascade operation
CascadeType. PERSIST Cascade persistence (save) operation
CascadeType. MERGE cascade update (merge) operation
CascadeType. REFRESH cascade refresh operation, only query acquisition operation
CascadeType. REMOVE cascade delete operation
CascadeType. ALL Cascade all the above operations
Fetch whether to delay loading. By default, the one with one means immediate loading, the one with more means delayed loading
mappedBy relationship maintenance
mappedBy= "parentid" indicates that the parentid attribute in the children class is used to maintain the relationship. This name must be exactly the same as the parentid attribute name in the children class.
Also note that the collection type in the parent class must be List or Set and cannot be set to ArrayList, otherwise an error will be reported
Demonstration effect (code download, note: this effect requires http to run, and the data in the effect is simulated data, not actually returned by the background, so the drop-down data of provinces, cities and counties you see are the same):
Note: This article uses the technical implementation of the previous related blogs. If necessary, you can click on the link below to learn more:
1) Detailed explanation of Javascript inheritance implementation: Provide a class.js to define the inheritance relationship between JavaScript classes and construction classes;
2) jquery skills allow any component to support DOM-like event management: provide an eventBase.js to provide DOM-like event management functions for any component instance;
3) Secondary encapsulation of jquery's ajax and ajax caching proxy components: AjaxCache: Provides ajax.js and ajaxCache.js, simplifies jquery's ajax call, and performs client-side caching proxy for requests.
Let’s first learn more about the requirements of this function.
1. Functional analysis
Use a cascading component containing three cascading items to illustrate this feature:
1) Each cascade item may require an option used as an input prompt:
In this case, an empty option can be selected in the data list of each cascade item (the one that prompts the input):
Options used as input prompts may also be unnecessary:
In this case, only data options can be selected in the data list of each cascade item, and empty options cannot be selected:
2) If the current page is queried from the database and the field corresponding to the cascading component has a value, then the queried value is echoed to the cascading component:
If the corresponding field queried has no value, then it will be displayed according to the two situations described in point 1).
3) Each cascade item forms a single linked list relationship in the data structure. The data list of the next cascade item is related to the data selected by the previous cascade item.
4) Considering performance issues, the data list of each cascade item is loaded and displayed asynchronously using ajax.
5) After the cascading component is initialized, automatically load the first list of cascading items.
6) When the previous cascade item changes, clear the data list of all directly or indirectly related cascade items. At the same time, if the changed value of the previous cascade item is not empty, it will be automatically loaded and directly related to it. The data list of the next cascading item. When clearing the data list of the cascading item, please note: If the cascading item needs to display an option for input prompts, the option must be retained when clearing.
7) Fully consider performance issues and avoid repeated loading.
8) Considering the problem of form submission, when any cascading item of the cascading component changes, the value selected by the cascading component must be reflected in a hidden text field, so that the value of the cascading component can be passed through the The text field is submitted to the background.
The functions are roughly the same as above.
2. Implementation ideas
1) Data structure
The cascading component is different from other components in that it has some dependencies on the background data. The data structure I considered that is easier to implement is:
{ "id": 1, "text": "北京市", "code": 110000, "parentId": 0 }, { "id": 2, "text": "河北省", "code": 220000, "parentId": 0 }, { "id": 3, "text": "河南省", "code": 330000, "parentId": 0 }
id is the unique identifier of data. The relationship between data is built through parentId. Text and code are common business fields. If we follow this data structure, our interface for querying the cascaded item data list will become very simple:
//查第一个级联项的列表 /api/cascade?parentId=0 //根据第一个级联项选的值,查第二个级联项的列表 /api/cascade?parentId=1 //根据第二个级联项选的值,查第三个级联项的列表 /api/cascade?parentId=4
This structure is also easy to handle for the backend. Although structurally they are a tree-shaped table structure, the queries are all single-layer, so it is easy to implement.
As can be seen from the previous query demonstration, this structure can easily help us unify the interface and parameters of data query into one, which is very convenient for component development. After we get this data structure from the background, we parse each piece of data into an option, such as 0c20d0abfbb000e0adad886ad473ea56Beijing City4afa15d3069109ac30911f04c56f3338, so that both It can complete the drop-down display of the data list, and can also collect the selected value of the current cascade item through the function of the select form element. Finally, when the cascade item changes, the selected option can also be obtained and stored on it. The value of data-param-value is used as the parentId parameter to load the next list of cascading items. This is also the idea of cascading component data query and analysis.
But what needs to be considered here is the issue of flexibility. In actual projects, the data structure of cascading components may be defined based on similar relationships such as id parentId, but their fields are not necessarily called id parentId text code, most likely another field. That is to say: when parsing data into options, it is uncertain which field is used to parse the text and value of the option, and what field value is used for the attribute data-param-value; there are also queries The parameter name parentId used for data cannot be fixed. Sometimes, if the backend staff has written the query interface first and uses another name, you cannot ask them to change their parameter names because they need it. Compiling and deploying is more troublesome than the front-end; and the 0 value of parentId=0 cannot be fixed, because the parentid of the first layer of data in the actual project may be empty or -1. These things must be designed as options. On the one hand, they provide default values, and at the same time, they are left to the outside to set according to the actual situation. For example, in the final implementation of this article, this option is defined like this:
textField: 'text', //The field name to be displayed in the 5a07473c87748fb1bf73f23d45547ab8 element in the returned data
valueField: 'text', //The field name to be set on the value of the 5a07473c87748fb1bf73f23d45547ab8 element in the returned data
paramField: 'id', //When calling the data query interface, the field name corresponding to the data to be passed to the background
paramName: 'parentId', //When calling the data query interface, pass the parameter name of the data after the url
defaultParam: '', //When querying the first cascade item, the value passed to the background is usually 0, '', or -1, etc., indicating that the upper level data is to be queried
2) html structure
According to item 1 of the previous functional analysis, there are two initial HTML structures for cascading components:
<ul id="licenseLocation-view" class="cascade-view clearfix"> <li> <select class="form-control"> <option value="">请选择省份</option> </select> </li> <li> <select class="form-control"> <option value="">请选择城市</option> </select> </li> <li> <select class="form-control"> <option value="">请选择区县</option> </select> </li> </ul>
or
<ul id="companyLocation-view" class="cascade-view clearfix"> <li> <select class="form-control"> </select> </li> <li> <select class="form-control"> </select> </li> <li> <select class="form-control"> </select> </li> </ul>
这两个结构唯一的区别就在于是否配置了用作输入提示的option。另外需要注意的是如果需要这个空的option,一定得把value属性设置成空,否则这个空的option在表单提交的时候会把option的提示信息提交到后台。
这两个结构最关键的是select元素,跟ul和li没有任何关系,ul跟li是为了UI而用到的;select元素没有任何语义,不用去标识哪个是省份,哪个是城市,哪个是区县。从功能上来说,一个select代表一个级联项,这些select在哪定义都不重要,我们只要告诉级联组件,它的级联项由哪些select元素构成就行了,唯一需要额外告诉组件的就是这些select元素的先后关系,但是这个通常都是用元素在html中的默认顺序来控制的。这个结构能够帮助我们把组件的功能尽可能地做到表现与行为分离。
3)职责分离和单链表的运用
从前面的部分也差不多能看出来了,这个级联组件如果按职责划分,可以分成两个核心的组件,一个负责整体功能和内部级联项的管理(CascadeView),另一个负责级联项的功能实现(CascadeItem)。另外为了更方便地实现级联的逻辑,我们只需要把所有的级联项通过链表连起来,通过发布-订阅模式,后一个级联项订阅前一个级联项发生改变的消息;当前面的级联项发生改变的时候,发布消息,通知后面的级联项去处理相关逻辑;通过链表的作用,这个消息可能可以一直传递到最后一个级联项为止。用图来描述的话,大致就是这个样子:
我们需要做的就是控制好消息的发布跟传递。
4)表单提交
为了能够方便地将级联组件的值提交到后台,可以把整个级联组件当成一个整体,对外提供一个onChanged事件,外部可通过这个事件获取所有级联项的值。由于存在多个级联项,所以在发布onChanged这个事件时,只能在任意级联项发生改变的时候,都去触发这个事件。
5)ajax缓存
在这个组件里面得考虑两个层级的ajax缓存,第一个是组件这一层级的,比如我把第一个级联项切换到了北京,这个时候第二个级联项就把北京的数据加载出来了,然后我把第一个级联项从北京切换到河北再切换到北京,这个时候第二个级联项要显示的还是北京的关联数据列表,如果我们在第一次加载这个列表的时候就把它的数据缓存下来了,那么这次就不用发起ajax请求了;第二个是ajax请求这一层级的,假如页面上有多个级联组件,我先把第一个级联组件的第一个级联项切换到北京,浏览器发起一个ajax请求加载数据,当我再把第二个级联组件的第一个级联项切换到北京的时候,浏览器还会再发一个请求去加载数据,如果我把第一个组件第一次ajax请求的返回的数据,先缓存起来,当第二个组件,用同样的参数请求同样的接口时,直接拿之前缓存觉得结果返回,这样也能减少一次ajax请求。第二个层级的ajax缓存依赖上文《对jquery的ajax进行二次封装以及ajax缓存代理组件:AjaxCache》,对于组件来说,它内部只实现了第一个层级的缓存,但是它不用考虑第二个层级的缓存,因为第二个层级的缓存实现对它来说是透明的,它不知道它用到的ajax组件有缓存的功能。
3. 实现细节
最终的实现包含了三个组件,CascadeView、CascadeItem、CascadePublicDefaults,前面两个是组件的核心,最后一个只是用来定义一些option,它的作用在CascadeItem的注释里面有详细的描述。另外在下面的代码中有非常详细的注释解释了一些关键代码的作用,结合着前面的需求来看代码,应该还是比较容易理解的。我以前倾向于用文字来解释一些实现细节,后来我慢慢觉得这种方式有点费力不讨好,第一是细节层面的语言不好组织,有的时候言不达意,明明想把一件事情解释清楚,结果反而弄得更加迷糊,至少我自己看自己写的东西就会这样的感触;第二是本身开发人员都具有阅读源码的能力,而且大部分积极的开发人员都愿意通过琢磨别人的代码来理解实现思路;所以我改用注释的方式来说明实现细节:)
CascadePublicDefaults:
define(function () { return { url: '',//数据查询接口 textField: 'text', //返回的数据中要在<option>元素内显示的字段名称 valueField: 'text', //返回的数据中要设置在<option>元素的value上的字段名称 paramField: 'id', //当调用数据查询接口时,要传递给后台的数据对应的字段名称 paramName: 'parentId', //当调用数据查询接口时,跟在url后面传递数据的参数名 defaultParam: '', //当查询第一个级联项时,传递给后台的值,一般是0,'',或者-1等,表示要查询第上层的数据 keepFirstOption: true, //是否保留第一个option(用作输入提示,如:请选择省份),如果为true,在重新加载级联项时,不会清除默认的第一个option resolveAjax: function (res) { return res; }//因为级联项在加载数据的时候会发异步请求,这个回调用来解析异步请求返回的响应 } });
CascadeView:
define(function (require, exports, module) { var $ = require('jquery'); var Class = require('mod/class'); var EventBase = require('mod/eventBase'); var PublicDefaults = require('mod/cascadePublicDefaults'); var CascadeItem = require('mod/cascadeItem'); /** * PublicDefaults的作用见CascadeItem组件内的注释 */ var DEFAULTS = $.extend({}, PublicDefaults, { $elements: undefined, //级联项jq对象的数组,元素在数据中的顺序代表级联的先后顺序 valueSeparator: ',', //获取所有级联项的值时使用的分隔符,如果是英文逗号,返回的值形如 北京市,区,朝阳区 values: '', //用valueSeparator分隔的字符串,表示初始时各个select的值 onChanged: $.noop //当任意级联项的值发生改变的时候会触发这个事件 }); var CascadeView = Class({ instanceMembers: { init: function (options) { //通过this.base调用父类EventBase的init方法 this.base(); var opts = this.options = this.getOptions(options), items = this.items = [], that = this, $elements = opts.$elements, values = opts.values.split(opts.valueSeparator); this.on('changed.cascadeView', $.proxy(opts.onChanged, this)); $elements && $elements.each(function (i) { var $el = $(this); //实例化CascadeItem组件,并把每个实例的prevItem属性指向前一个实例 //第一个prevItem属性设置为undefined var cascadeItem = new CascadeItem($el, $.extend(that.getItemOptions(), { prevItem: i == 0 ? undefined : items[i - 1], value: $.trim(values[i]) })); items.push(cascadeItem); //每个级联项实例发生改变都会触发CascadeView组件的changed事件 //外部可在这个回调内处理业务逻辑 //比如将所有级联项的值设置到一个隐藏域里面,用于表单提交 cascadeItem.on('changed.cascadeItem', function () { that.trigger('changed.cascadeView', that.getValue()); }); }); //初始化完成自动加载第一个级联项 items.length && items[0].load(); }, getOptions: function (options) { return $.extend({}, this.getDefaults(), options); }, getDefaults: function () { return DEFAULTS; }, getItemOptions: function () { var opts = {}, _options = this.options; for (var i in PublicDefaults) { if (PublicDefaults.hasOwnProperty(i) && i in _options) { opts[i] = _options[i]; } } return opts; }, //获取所有级联项的值,是一个用valueSeparator分隔的字符串 //为空的级联项的值不会返回 getValue: function () { var value = []; this.items.forEach(function (item) { var val = $.trim(item.getValue()); val != '' && value.push(val); }); return value.join(this.options.valueSeparator); } }, extend: EventBase }); return CascadeView; });
CascadeItem:
define(function (require, exports, module) { var $ = require('jquery'); var Class = require('mod/class'); var EventBase = require('mod/eventBase'); var PublicDefaults = require('mod/cascadePublicDefaults'); var AjaxCache = require('mod/ajaxCache'); //这是一个可缓存的Ajax组件 var Ajax = new AjaxCache(); /** * 有一部分option定义在PublicDefaults里面,因为CascadeItem组件不会被外部直接使用 * 外部用的是CascadeView组件,所以有一部分的option必须变成公共的,在CascadeView组件也定义一次 * 外部通过CascadeView组件传递所有的option * CascadeView内部实例化CascadeItem的时候,再把PublicDefaults内的option传递给CascadeItem */ var DEFAULTS = $.extend({}, PublicDefaults, { prevItem: undefined, // 指向前一个级联项 value: '' //初始时显示的value }); var CascadeItem = Class({ instanceMembers: { init: function ($el, options) { //通过this.base调用父类EventBase的init方法 this.base($el); this.$el = $el; this.options = this.getOptions(options); this.prevItem = this.options.prevItem; //前一个级联项 this.hasContent = false;//这个变量用来控制是否需要重新加载数据 this.cache = {};//用来缓存数据 var that = this; //代理select元素的change事件 $el.on('change', function () { that.trigger('changed.cascadeItem'); }); //当前一个级联项的值发生改变的时候,根据需要做清空和重新加载数据的处理 this.prevItem && this.prevItem.on('changed.cascadeItem', function () { //只要前一个的值发生改变并且自身有内容的时候,就得清空内容 that.hasContent && that.clear(); //如果不是第一个级联项,同时前一个级联项没有选中有效的option时,就不处理 if (that.prevItem && $.trim(that.prevItem.getValue()) == '') return; that.load(); }); var value = $.trim(this.options.value); value !== '' && this.one('render.cascadeItem', function () { //设置初始值 that.$el.val(value.split(',')); //通知后面的级联项做清空和重新加载数据的处理 that.trigger('changed.cascadeItem'); }); }, getOptions: function (options) { return $.extend({}, this.getDefaults(), options); }, getDefaults: function () { return DEFAULTS; }, clear: function () { var $el = this.$el; $el.val(''); if (this.options.keepFirstOption) { //保留第一个option $el.children().filter(':gt(0)').remove(); } else { //清空全部 $el.html(''); } //通知后面的级联项做清空和重新加载数据的处理 this.trigger('changed.cascadeItem'); this.hasContent = false;//表示内容为空 }, load: function () { var opts = this.options, paramValue, that = this, dataKey; //dataKey是在cache缓存时用的键名 //由于第一个级联项的数据是顶层数据,所以在缓存的时候用的是固定且唯一的键:root //其它级联项的数据缓存时用的键名跟前一个选择的option有关 if (!this.prevItem) { paramValue = opts.defaultParam; dataKey = 'root'; } else { paramValue = this.prevItem.getParamValue(); dataKey = paramValue; } //先看数据缓存中有没有加载过的数据,有就直接显示出来,避免Ajax if (dataKey in this.cache) { this.render(this.cache[dataKey]); } else { var params = {}; params[opts.paramName] = paramValue; Ajax.get(opts.url, params).done(function (res) { //resolveAjax这个回调用来在外部解析ajax返回的数据 //它需要返回一个data数组 var data = opts.resolveAjax(res); if (data) { that.cache[dataKey] = data; that.render(data); } }); } }, render: function (data) { var html = [], opts = this.options; data.forEach(function (item) { html.push(['<option value="', item[opts.valueField], '" data-param-value="',//将paramField对应的值存放在option的data-param-value属性上 item[opts.paramField], '">', item[opts.textField], '</option>'].join('')); }); //采用append的方式动态添加,避免影响第一个option //最后还要把value设置为空 this.$el.append(html.join('')).val(''); this.hasContent = true;//表示有内容 this.trigger('render.cascadeItem'); }, getValue: function () { return this.$el.val(); }, getParamValue: function () { return this.$el.find('option:selected').data('paramValue'); } }, extend: EventBase }); return CascadeItem; });
4. demo说明
演示代码的结构:
其中框起来的就是演示的相关部分。html/regist.html是演示效果的页面,js/app/regist.js是演示效果的入口js:
define(function (require, exports, module) { var $ = require('jquery'); var CascadeView = require('mod/cascadeView'); function publicSetCascadeView(fieldName, opts) { this.cascadeView = new CascadeView({ $elements: $('#' + fieldName + '-view').find('select'), url: '../api/cascade.json', onChanged: this.onChanged, values: opts.values, keepFirstOption: this.keepFirstOption, resolveAjax: function (res) { if (res.code == 200) { return res.data; } } }); } var LOCATION_VIEWS = { licenseLocation: { $input: $('input[name="licenseLocation"]'), keepFirstOption: true, setCascadeView: publicSetCascadeView, onChanged: function(e, value){ LOCATION_VIEWS.licenseLocation.$input.val(value); } }, companyLocation: { $input: $('input[name="companyLocation"]'), keepFirstOption: false, setCascadeView: publicSetCascadeView, onChanged: function(e, value){ LOCATION_VIEWS.companyLocation.$input.val(value); } } }; LOCATION_VIEWS.licenseLocation.setCascadeView('licenseLocation', { values: LOCATION_VIEWS.licenseLocation.$input.val() }); LOCATION_VIEWS.companyLocation.setCascadeView('companyLocation', { values: LOCATION_VIEWS.companyLocation.$input.val() }); });
注意以上代码中LOCATION_VIEWS这个变量的作用,因为页面上有多个级联组件,这个变量其实是通过策略模式,把各个组件的相关的东西都用一种类似的方式管理起来而已。如果不这么做的话,很容易产生重复代码;这种形式也比较有利于在入口文件这种处理业务逻辑的地方,进行一些业务逻辑的分离与封装。
5. others
这估计是在现在公司写的最后一篇博客,过两天就得去新单位去上班了,不确定还能否有这么多空余的时间来记录平常的工作思路,但是好歹已经培养了写博客的习惯,将来没时间也会挤出时间来的。今年的目标主要是拓宽知识面,提高代码质量,后续的博客更多还是在组件化开发这个类别上,希望以后能够得到大家的继续关注脚本之家网站!