PubAndSub

发布订阅

AddEventListens

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
class EventEmitter{
//事件处理函数集合
handlers = {
//click [handler1,handler2,handler3]
}

//订阅 addEventListener
//type click once 订阅次数
on(type,handler,once){
//当前事件类型是否存在
if(!this.handlers[type]){
//不存在则声明定义
this.handlers[type] = []
}

//当前事件类型是否存在该方法
if(!this.handlers[type].includes(handler)){
//不存在则push该方法
this.handlers[type].push(handler)
//是否只执行一次
handler.once = once
}
}

once(type,handler){
this.on(type,handler,true)
}

//解绑
off(type,handler){
if(this.handlers[type]){
this.handlers[type] = this.handlers[type].filter(h=>{
return h !== handler
})
}
}

trigger(type){
if(this.handlers[type]){
this.handlers[type].forEach(handler=>{
handler.call(this)
if(handler.once){
this.off(type,handler)
}
})
}
}
}

const ev = new EventEmitter()

function handler1 (){
console.log('handler1');
}

function handler2 (){
console.log('handler2');
}

function handler3 (){
console.log('handler3' );
}

ev.on('test',handler1)
ev.on('test',handler2)
ev.on('test',handler3)


ev.trigger('test')
ev.trigger('test')