订阅-发布设计模式实践
Event bus
event bus既是node中各个模块的基石,又是前端组件通信的依赖手段之一,同时涉及了订阅-发布设计模式,是非常重要的基础。
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
|
class EventEmitter {
constructor() {
this._events = this._events || new Map();
}
}
EventEmitter.prototype.emit = function(type, ...args) {
const handler = this._events.get(type);
if (Array.isArray(handler)) {
handler.forEach(h => {
if (args.length > 0) {
h.apply(this, args)
} else {
h.call(this)
}
})
} else {
if (args.length > 0) {
handler.apply(this, args)
} else {
handler.call(this)
}
}
}
EventEmitter.prototype.addListener = function(type, fn) {
const handler = this._events.get(type)
if (!handler) {
this._events.set(type, fn);
} else if (handler && typeof handler === 'function') {
this._events.set(type, [handler, fn])
} else {
handler.push(fn)
}
}
EventEmitter.prototype.removeListener = function(type, fn) {
const handler = this._events.get(type)
if (handler && typeof handler === 'function') {
this._events.delete(type)
} else {
let position
handler.forEach((h, i) => {
if (h === fn) {
position = i
} else {
position = -1
}
})
if (position !== -1) {
handler.splice(position, 1)
if (handler.length === 1) {
this._events.set(type, handler[0])
}
} else {
return this;
}
}
}
|