-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
136 lines (102 loc) · 2.86 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
class MPStore {
constructor() {
this.data = {};
}
get(key, nameSpace) {
if (nameSpace) {
key = `${nameSpace}_${key}`;
}
return this[key];
}
set(key, value) {
if (!value) {
const { key: k, nameSpace, value: v } = key;
value = v;
key = nameSpace ? `${nameSpace}_${k}` : k;
}
this[key] = value;
return this;
}
logout(instance, key, nameSpace) {
// 给了key 给了nameSpace
if (key && nameSpace) {
// 容错
if (!this.data[nameSpace]) return this;
const { refs = [] } = this.data[nameSpace][key];
refs.splice(refs.findIndex(ref => ref === instance), 1);
return this;
}
// 给了key 没给nameSpace
if (key && !nameSpace) {
// 所有nameSpace下的这个key都删掉
for (const nameSpaceValue of Object.values(this.data)) {
if (!nameSpaceValue[key]) return this;
const refs = nameSpaceValue[key].refs;
refs.splice(refs.findIndex(ref => ref === instance), 1);
}
return this;
}
// 如果两个都没给 就全清理了
for (const nameSpaceValue of Object.values(this.data)) {
for (const [, { refs = [] }] of Object.entries(nameSpaceValue)) {
refs.splice(refs.findIndex(ref => ref === instance), 1);
}
}
return this;
}
register(key, instance) {
let defaultValue = undefined;
let beforeUpdate = () => {};
let afterUpdate = () => {};
let nameSpace = 'global';
// 重载参数
if (!instance) {
beforeUpdate = key.beforeUpdate || beforeUpdate;
afterUpdate = key.afterUpdate || afterUpdate;
defaultValue = key.defaultValue;
instance = key.instance || instance;
nameSpace = key.nameSpace || nameSpace;
key = key.key;
}
// 处理命名空间
if (!this.data[nameSpace]) {
this.data[nameSpace] = {};
}
const dataSet = this.data[nameSpace];
const realKey = nameSpace === 'global' ? key : `${nameSpace}_${key}`;
if (dataSet[key]) {
if (!dataSet[key].refs.includes(instance)) {
dataSet[key].refs.push(instance);
}
instance.setData({
[realKey]: dataSet[key].value || defaultValue,
});
return;
}
Object.defineProperty(this, realKey, {
get() {
return dataSet[key].value;
},
set(value) {
dataSet[key].refs.forEach((instance) => {
if (instance.setData) {
beforeUpdate(dataSet[key].value, value);
dataSet[key].value = value;
instance.setData({
[realKey]: value,
});
afterUpdate(value);
}
});
},
});
dataSet[key] = {
refs: [instance],
value: undefined,
};
this[realKey] = defaultValue;
}
}
export const Store = MPStore;
const store = new MPStore();
export default store;