/
event_target.ts
67 lines (54 loc) · 1.65 KB
/
event_target.ts
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
import { isArray, isObject, warn } from '@tarojs/shared'
interface EventListenerOptions {
capture?: boolean;
}
interface AddEventListenerOptions extends EventListenerOptions {
once?: boolean;
passive?: boolean;
}
export interface EventHandler extends Function {
_stop?: boolean;
}
export class TaroEventTarget {
protected __handlers: Record<string, EventHandler[]> = {}
public addEventListener (type: string, handler: EventHandler, options?: boolean | AddEventListenerOptions) {
type = type.toLowerCase()
const handlers = this.__handlers[type]
let isCapture = Boolean(options)
let isOnce = false
if (isObject<AddEventListenerOptions>(options)) {
isCapture = Boolean(options.capture)
isOnce = Boolean(options.once)
}
if (isOnce) {
const wrapper = function () {
handler.apply(this, arguments) // this 指向 Element
this.removeEventListener(type, wrapper)
}
this.addEventListener(type, wrapper, {
...(options as AddEventListenerOptions),
once: false
})
return
}
warn(isCapture, 'The event capture feature is unimplemented.')
if (isArray(handlers)) {
handlers.push(handler)
} else {
this.__handlers[type] = [handler]
}
}
public removeEventListener (type: string, handler: EventHandler) {
type = type.toLowerCase()
if (handler == null) {
return
}
const handlers = this.__handlers[type]
if (!isArray(handlers)) {
return
}
const index = handlers.indexOf(handler)
warn(index === -1, `事件: '${type}' 没有注册在 DOM 中,因此不会被移除。`)
handlers.splice(index, 1)
}
}