前言
在 做 可视化的时候 ,我们的页面展示 全部是 是由JSON 处理来的 而组件 的 方法 都是写在组件内的 ,在布局复杂的JSON 里面去单独找方法 找数据,代码容易混乱
结论 :事件系统 来进行 统一处理
核心难点
- 遍历数据中的所有function
- function 参数获取
- 插入 自定义 function
// 1. 遍历所有的function
const treeDay = (list, obj, id) => {
id = obj.id || id;
const type = Object.prototype.toString.call(list);
// 判断简单类型
const isSimpleType = (type) => {
return (
['[object String]', '[object Number]', '[object Boolean]'].indexOf(
type,
) > -1
);
};
// 判断是否是 简单类型
if (isSimpleType(type)) return list;
if (Array.isArray(list)) {
list = list.map((c) => {
return treeDay(c, c, id);
});
} else if (type === '[object Object]') {
const newList = {};
Object.keys(list).forEach((c) => {
const eb = list[c];
newList[c] = isSimpleType(Object.prototype.toString.call(eb))
? eb
: treeDay(eb, list, id);
});
list = newList;
} else if (typeof list === 'function') {
// 设置 别名
let er = getFunParam(list);
const nlist = Object.assign({ fun: list });
list = function () {
er = Array.prototype.slice.call(arguments);
console.log(list.name, er, id);
return nlist.fun(...er);
};
}
return list;
};
return treeDay(comps, {}, 'page');
// 2. 获取 function 的 参数
const getFunParam = (fn) => {
return /\(\s*([\s\S]*?)\s*\)/.exec(fn)[1].split(/\s*,\s*/);
};
// 3. 插入自定义function
let er = getFunParam(list);
const nlist = Object.assign({ fun: list });
list = function () {
er = Array.prototype.slice.call(arguments);
console.log(list.name, er, id);
return nlist.fun(...er);
};
demo: