-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPubSub.js
35 lines (31 loc) · 863 Bytes
/
PubSub.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
class PubSub {
constructor() {
this.handlers = {};
}
// 订阅事件
on(eventType, handler) {
if (this.handlers[eventType]) {
this.handlers[eventType].push(handler);
} else {
this.handlers[eventType] = [handler];
}
}
// 消息发布
emit(eventType, ...args) {
const handlers = this.handlers[eventType];
if (!handlers || handlers.length === 0) {
return false;
}
handlers.forEach(handler => handler.call(null, ...args));
return true;
}
// 取消
remove(eventType, handler) {
const handles = this.handlers[eventType] || [];
if (!handles || !handles.length) {
return;
}
this.handlers[eventType].splice(handles.indexOf(handler) >>> 0, 1);
}
}
module.exports = PubSub;