-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathev.html
62 lines (52 loc) · 1.53 KB
/
ev.html
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
<html>
<head>
<title></title>
</head>
<body>
<button id="jianting">监听</button>
<button id="emit">触发</button>
<button id="remove">移除</button>
</body>
<script>
// JavaScript 的对象(Object),本质上是键值对的集合(Hash 结构),但是传统上只能用字符串当作键。这给它的使用带来了很大的限制.es6 map“键”的范围不限于字符串,各种类型的值(包括对象)都可以当作键
class Event {
constructor() {
this.events = this.events || new Map(); // 储存事件 键值对
}
// 触发
emit(type, args) {
// 从已有的事件中找当前触发的事件
let handler = this.events.get(type);
if(handler) {
// apply允许我们将一个数组"解开"成为一个个的参数再传递给调用函数
// handler.apply(this, args)
handler(args)
}
}
// 监听
on(type, fn) {
if(!this.events.get(type)) {
this.events.set(type, fn)
}
}
// 移除
removeListener(type) {
if(this.events.has(type)) {
this.events.delete(type);
}
}
}
let ev = new Event();
document.getElementById('jianting').onclick = () => {
ev.on('change', (msg) => {
console.log(msg)
})
}
document.getElementById('emit').onclick = () => {
ev.emit('change', [222, 123, 344])
}
document.getElementById('remove').onclick = () => {
ev.removeListener('change')
}
</script>
</html>