-
Notifications
You must be signed in to change notification settings - Fork 4
/
addEvent.js.html
111 lines (88 loc) · 2.94 KB
/
addEvent.js.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
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>addEvent.js</title>
</head>
<body>
<div id="outerone">
<div id="one">干我</div>
</div>
<script>
//addEvent即为DOM元素绑定事件
// a counter used to create unique IDs
//为每一个事件添加唯一的id
addEvent.guid = 1;
function addEvent(element, type, handler) {
// assign each event handler a unique ID
//如果用户自定义的回调函数没有$$guid的话,
//为每个handler添加唯一的id
if (!handler.$$guid) handler.$$guid = addEvent.guid++;
// create a hash table of event types for the element
//为目标元素添加events属性
if (!element.events) element.events = {};
// create a hash table of event handlers for each element/event pair
//events是目标元素绑定的事件的集合
//第一次使用addEvent绑定往往是undefined
let handlers = element.events[type];
if (!handlers) {
handlers = element.events[type] = {};
// store the existing event handler (if there is one)
//handlers的0属性作为目标元素的原生绑定事件
if (element["on" + type]) {
handlers[0] = element["on" + type];
}
}
// store the event handler in the hash table
//将每次绑定的事件保存到handler的id属性中
handlers[handler.$$guid] = handler;
// assign a global event handler to do all the work
//为目标元素的原生事件绑定处理程序(handleEvent)
element["on" + type] = handleEvent;
}
//移除监听事件
function removeEvent(element, type, handler) {
// delete the event handler from the hash table
console.log(handler,'handler52')
if (element.events && element.events[type]) {
delete element.events[type][handler.$$guid];
}
}
//执行事件的处理程序
function handleEvent(event) {
// grab the event object (IE uses a global event object)
// console.log(event,'event55')
//event即MouseEvent,原生的鼠标事件集合
event = event || window.event;
// get a reference to the hash table of event handlers
//找到相同事件的处理程序
//注意这个this,指的是目标元素
//找到handlers集合
let handlers = this.events[event.type];
// execute each event handler
//依次执行事件的处理程序
for (let i in handlers) {
this.$$handleEvent = handlers[i];
this.$$handleEvent(event);
}
}
// function handleEvent(event) {
// event = event || window.event;
// for (let i in this.events[event.type]) {
// console.log(this,'this80')
// this.events[event.type][i](event)
// }
// }
let one=document.querySelector("#one")
addEvent(one,'click',function () {
console.log('点击了one')
})
// removeEvent(one,'click',function () {
// console.log('点击了one')
// })
// one.onclick=function (e) {
// console.log('原生点击了one')
// }
</script>
</body>
</html>