-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
133 lines (126 loc) · 2.78 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
/*
* @Author: moses.zhou
* @Date: 2019-02-20 09:03:31
* @Last Modified by: moses.zhou
* @Last Modified time: 2019-02-20 09:12:49
*
* const readyListener = eventManger.addEventListener("ready",(params)=>{ doing sth.});
*
*
* readyListener.remove()
*
*/
/**
* @description: 事件管理器
*/
class EventManager {
constructor() {
this._events = [];
this._eventId = 0;
}
/**
*
* @param {string} name
* @param {(data:object,endFn:()=>{})=>{}} fn 事件处理函数,以waterfallEmit触发时, 如果提供了endFn,则表示结束瀑布流
* @returns {{remove:()=>{}}}
*/
addEventListener(name, fn) {
const id = this._eventId++;
this._events.push({
id,
name,
fn,
});
return {
remove: () => {
this.removeEventListener({ id });
},
};
}
/**
*
* @param {string} name
* @param {()=>{}} fn
*/
once(name, fn) {
const id = this._eventId++;
const remove = () => {
this.removeEventListener({ id });
};
this._events.push({
id,
name,
fn: (params) => {
remove();
fn(params);
},
});
}
/**
*
* @param {{id:number}} param0
*/
removeEventListener({ id }) {
const i = this._events.findIndex((x) => x.id === id);
if (i > -1) {
this._events.splice(i, 1);
}
}
/**
*
* @param {string} name
* @param {object} params
*/
emit(name, params) {
if (name) {
// console.log(`emitter event:${name}`);
const events = this._events.filter((x) => x.name === name);
// console.assert(events.length == 0, `'${name}'事件还未有程序注册`);
for (let i = events.length - 1; i >= 0; i--) {
if (events[i].fn(params) === true) {
return;
}
}
}
}
/**
* @description: 瀑布流式事件触发(倒序触发),事件注册的函数返回值作为下一个事件的参数,如果想结束瀑布流,在订阅函数中调用endFn()
* @param {string} name
* @param {object} params
* @returns {object}
*/
waterfallEmit(name, params) {
if (name) {
// console.log(`emitter event:${name}`);
const events = this._events.filter((x) => x.name === name);
// console.assert(events.length == 0, `'${name}'事件还未有程序注册`);
let data = params;
let isEnd = false;
for (let i = events.length - 1; i >= 0; i--) {
data = events[i].fn(data, () => {
isEnd = true;
});
if (isEnd) {
break;
}
}
return data;
}
}
/**
*
* @param {string} name
* @param {object} params
*/
trigger(name, params) {
this.emit(name, params);
}
/**
*
*/
clear() {
this._events = [];
}
}
export default new EventManager();
export { EventManager };