/* * 存储地区级联数据, 整个项目有且只加载一次 地区级联数据请求。 */ export const cascaderCacheData = (function () { let data = []; let isWriting = false; let clientList = [];//搜集所有的监听 事件; function cascaderSetData() { const newData = Array.prototype.shift.call(arguments); if (Object.prototype.toString.call(newData) !== "[object Array]") { throw new Error('Expected the arguments to be a Array.'); } if (newData.length != 0 && data.length === 0) { //data只能写入一次,不能重复添加。 data = data.concat(newData); if (clientList.length !== 0) { clientList.map(val => val(data)); clientList = []; } return; } } function cascaderGetData() { return data.slice(); } function writeSetData() { isWriting = true; } function writeGetData(cb) { return isWriting; } function subscribe(cb) { clientList.push(cb);//存储待执行的事件 } return function () { return { cascaderGetData, cascaderSetData, writeSetData, writeGetData, subscribe } } })(); /* * 存储下拉框数据, 同一个类型的下来框数据,有且只 加载一次 */ export const moreSelcetData = (function () { let currentData = {}; let clientList = [];//存储所有的监听 事件; let isWriting = [];//存储 正在请求的类型 function isPlainObject(obj) { if (typeof obj !== 'object' || obj === null) return false let proto = obj while (Object.getPrototypeOf(proto) !== null) { proto = Object.getPrototypeOf(proto) } return Object.getPrototypeOf(obj) === proto } function setDataMoreSelcet() { const newData = Array.prototype.shift.call(arguments); if (!isPlainObject(newData)) { throw new Error('Expected the arguments to be a Object.'); } Object.entries(newData).map( ([key, value], index) => { if (!(key in currentData)) { currentData[key] = value; } }); if (clientList.length !== 0) { const strCache = JSON.stringify(clientList); clientList.map(({type, func}, index) => { if (type in currentData && isWriting.includes(type)) { func({[type]: currentData[type]}, type); // if (!new RegExp(`\{type:${type}`).test(strCache)) { // const i = isWriting.indexOf(type); // console.error("isWriting", isWriting) // isWriting.splice(i, 1); // } } }); } } function getDataMoreSelcet(type, cache) { if (!type) { return; } if (type in currentData && cache) { return Object.assign({}, {[type]: currentData[type]}); } return false; } function subscribe(obj) { if (isPlainObject(obj)) { clientList.push(obj);//存储待执行的事件 } } function setWritingState(type) { isWriting.push(type); } function ifWrited(type) { return isWriting.includes(type); } return function () { return { setDataMoreSelcet, getDataMoreSelcet, subscribe, setWritingState, ifWrited } } })();