@sheto/emiter 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.js +47 -0
- package/package.json +10 -0
- package/types/index.d.ts +14 -0
package/index.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
export const EmiterPlugin = {
|
|
2
|
+
queue: [],
|
|
3
|
+
actions: {},
|
|
4
|
+
timer: null,
|
|
5
|
+
release(eventNames) {
|
|
6
|
+
for (const key of eventNames) {
|
|
7
|
+
Reflect.deleteProperty(this.actions, key);
|
|
8
|
+
}
|
|
9
|
+
},
|
|
10
|
+
emit(eventName, payload) {
|
|
11
|
+
const needExcution = this.actions[eventName];
|
|
12
|
+
if (Array.isArray(needExcution) && needExcution.length > 0) {
|
|
13
|
+
for (const action of needExcution) {
|
|
14
|
+
action(payload);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
else {
|
|
18
|
+
this.queue.push({
|
|
19
|
+
name: eventName,
|
|
20
|
+
payload
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
on(eventName, action) {
|
|
25
|
+
// 监听事件
|
|
26
|
+
if (eventName in this.actions && Array.isArray(this.actions[eventName])) {
|
|
27
|
+
this.actions[eventName].push(action);
|
|
28
|
+
}
|
|
29
|
+
else {
|
|
30
|
+
this.actions[eventName] = [
|
|
31
|
+
action
|
|
32
|
+
];
|
|
33
|
+
}
|
|
34
|
+
// 检测注册事件是否有在注册之前提前触发
|
|
35
|
+
const waitExcution = this.queue.findIndex((emitedEventName) => emitedEventName.name === eventName);
|
|
36
|
+
if (waitExcution > -1) {
|
|
37
|
+
if (this.timer) {
|
|
38
|
+
clearTimeout(this.timer);
|
|
39
|
+
}
|
|
40
|
+
action(this.queue[waitExcution].payload);
|
|
41
|
+
this.timer = setTimeout(() => {
|
|
42
|
+
this.queue.splice(waitExcution, 1);
|
|
43
|
+
}, 1000);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
export default EmiterPlugin;
|
package/package.json
ADDED
package/types/index.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
type actionType = (payload?: any) => void;
|
|
2
|
+
interface EmiterType {
|
|
3
|
+
timer: null | number;
|
|
4
|
+
queue: {
|
|
5
|
+
name: string;
|
|
6
|
+
payload: any;
|
|
7
|
+
}[];
|
|
8
|
+
actions: Record<string, actionType[]>;
|
|
9
|
+
emit: (eventName: string, payload?: any) => void;
|
|
10
|
+
on: (eventName: string, action: actionType) => void;
|
|
11
|
+
release(eventNames: string[]): void;
|
|
12
|
+
}
|
|
13
|
+
export declare const EmiterPlugin: EmiterType;
|
|
14
|
+
export default EmiterPlugin;
|