You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 lines
2.5 KiB

2 years ago
# BI.config的执行顺序是什么,为什么这么设计.md
BI.config配置的方法除了`bi.provider.system`直接执行之外,全都是在获取资源的时候执行
对于旧版本的FineUI, config配置的函数是在`BI.init()`中执行的,`BI.init()`又是在什么时候调用的呢,是在第一次`BI.createWidget()`时候调用的.
这样带来了一个弊端,如果`BI.init()`先被调用了,那么后续`BI.config()`的内容将不再执行
例如如下代码,javascript文件加载顺序为abcd,在旧有设计中,d.js获取的items长度是几?答案是1,因为在b.js中调用了`BI.Msg.toast`方法,而这个方法一定会间接的调用到`BI.init()`,这是不可控的,因为我们无法控制开发者要怎么写代码.很多时候出了bug,但是面对茫茫多的插件,完全不知道是由哪个文件引发的.
```
// a.js
BI.constant("bi.constant.items", [
{
id: 1,
text: 1,
},
]);
// b.js
BI.Msg.toast("123");
// c.js
BI.config("bi.constant.items", items => {
items.push({
id: 2,
text: 2,
});
return items;
});
// d.js
var items = BI.Constants.getConstant("bi.constant.items"); // 有几个?
```
BI.config注册的方法结构是什么样呢?
```
interface configFunctions {
[key: string]: Function[];
}
```
`BI.config`的配置函数是如何执行的呢?
对于每一个资源,都有一个配置函数队列,在每次获取资源的时候执行队列中的配置方法,顺序执行然后清空队列,如果之后再调用`BI.config`配置当前资源,重新讲配置函数加入队列中
```
BI.constant("bi.constant.items", [
{
id: 1,
text: 1,
},
]);
// 此时资源bi.constant.items的配置函数队列中只有一个配置方法等待执行
BI.config("bi.constant.items", items => {
items.push({
id: 2,
text: 2,
});
return items;
});
// 获取资源的是执行并清空了队列
var items = BI.Constants.getConstant("bi.constant.items"); // 2个
// 又给资源bi.constant.items的配置函数队列中增加了一个配置方法等待执行
BI.config("bi.constant.items", items => {
items.push({
id: 3,
text: 3,
});
return items;
});
// 获取资源的是又执行并清空了队列
items = BI.Constants.getConstant("bi.constant.items"); // 3个
```
这样设计有什么好处呢?
首先在获取资源时候才执行配置函数,完全避免了js加载顺序所带来的隐患,其次使配置可以无需立即执行并且可以多次配置.