-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpubsub.js
More file actions
123 lines (115 loc) · 3.1 KB
/
pubsub.js
File metadata and controls
123 lines (115 loc) · 3.1 KB
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
/**
* 事件中心
* 发布者和订阅者互相不知道对方的存在
*/
class EventHub {
constructor() {
// 事件中心
// 存储格式: { warTask: [], routeTask: [] }
// 每种事件(任务)下存放其订阅者的回调函数
this.events = {}
}
/**
* 订阅
* @param {string} type
* @param {Function} cb
*/
subscribe(type, cb) {
if (!this.events[type]) {
this.events[type] = []
}
this.events[type].push(cb)
}
/**
* 发布
* @param {string} type
* @param {...any} args
*/
publish(type, ...args) {
if (this.events[type]) {
this.events[type].forEach((cb) => cb(...args))
}
}
/**
* 取消订阅
* @param {string} type
* @param {Function} cb
*/
unsubscribe(type, cb) {
const cbList = this.events[type]
if (cbList) {
const cbIndex = cbList.findIndex((e) => e === cb)
if (cbIndex != -1) {
cbList.splice(cbIndex, 1)
}
}
if (cbList.length === 0) {
Reflect.deleteProperty(this.events, type)
}
}
/**
* @param {string} type
*/
unsubscribeAll(type) {
if (this.events[type]) {
Reflect.deleteProperty(this.events, type)
}
}
}
class Publisher {
/**
* @param {EventHub} eventHub
*/
constructor(eventHub) {
this.eventHub = eventHub
}
/**
* @param {string} event
* @param {...any} args
*/
publish(event, ...args) {
this.eventHub.publish(event, ...args)
}
}
class Subscriber {
/**
* @param {EventHub} eventHub
*/
constructor(eventHub) {
this.eventHub = eventHub
}
/**
* @param {string} event
* @param {Function} handler
*/
subscribe(event, handler) {
this.eventHub.subscribe(event, handler)
}
}
function main() {
// 创建一个任务中心
const eventHub = new EventHub()
const sub1 = new Subscriber(eventHub)
const sub2 = new Subscriber(eventHub)
const pub1 = new Publisher(eventHub) // 负责战斗任务
const pub2 = new Publisher(eventHub) // 负责日常任务
// 玩家一订阅战斗任务
sub1.subscribe('warTask', (taskInfo) => {
console.log('sub1 收到宗门殿发布战斗任务,任务信息:' + taskInfo)
})
// 玩家一订阅日常任务
sub1.subscribe('routeTask', (taskInfo) => {
console.log('sub1 收到宗门殿发布日常任务,任务信息:' + taskInfo)
})
// 玩家二订阅全类型任务
sub2.subscribe('allTask', (taskInfo) => {
console.log('sub2 收到宗门殿发布五星任务,任务信息:' + taskInfo)
})
// 发布战斗任务
pub1.publish('warTask', '猎杀时刻')
pub1.publish('allTask', '猎杀时刻')
// 发布日常任务
pub2.publish('routeTask', '种树浇水')
pub2.publish('allTask', '种树浇水')
}
main()