-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path手写一个delegate.js
50 lines (48 loc) · 1.17 KB
/
手写一个delegate.js
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
!function(win, doc) {
class Delegator {
constructor(selector) {
this.root = doc.querySelector(selector)
this.events = {}
}
on(event, target, fn) {
if(!this.events[event]) {
this.events[event] = []
}
this.events[event].push({
target,
cb:fn
})
this.root.addEventListener(event, this._delegate)
return this
}
_delegate(e) {
let target = e.target || e.srcElement
let currentTarget = e.currentTarget
while(target !== currentTarget) {
this.eventsObj[e.type].forEach(item => {
//查找订阅事件者
if(target.matches(item.selector)){
//执行订阅事件者携带的函数
item.callback.call(target,e);
}
});
//往上冒泡
target = target.parentNode;
}
}
}
}(window, document)
function delegate(element, eventType, selector, fn) {
element.addEventListener(eventType, (e) => {
let el = e.target;
while (!el.matches(selector)) {
if (element === el) {
el = null;
break;
}
el = el.parentNode;
}
el && fn.call(el, e, el);
});
return element;
}