-
Notifications
You must be signed in to change notification settings - Fork 237
/
Copy pathEventTarget.js
103 lines (87 loc) · 3.11 KB
/
EventTarget.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
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
const _events = new WeakMap()
class Touch {
constructor(touch) {
// CanvasTouch{identifier, x, y}
// Touch{identifier, pageX, pageY, clientX, clientY, force}
this.identifier = touch.identifier
const doubleQuestionFunc = (valueA, valueB) =>
valueA !== null && valueA !== void 0 ? valueA : valueB;
this.force = touch.force === undefined ? 1 : touch.force
this.pageX = doubleQuestionFunc(touch.pageX, touch.x);
this.pageY = doubleQuestionFunc(touch.pageY, touch.y);
this.clientX = doubleQuestionFunc(touch.clientX, touch.x);
this.clientY = doubleQuestionFunc(touch.clientY, touch.y);
this.screenX = this.pageX
this.screenY = this.pageY
}
}
export default class EventTarget {
constructor() {
_events.set(this, {})
}
addEventListener(type, listener, options = {}) {
let events = _events.get(this)
if (!events) {
events = {}
_events.set(this, events)
}
if (!events[type]) {
events[type] = []
}
events[type].push(listener)
if (options.capture) {
// console.warn('EventTarget.addEventListener: options.capture is not implemented.')
}
if (options.once) {
// console.warn('EventTarget.addEventListener: options.once is not implemented.')
}
if (options.passive) {
// console.warn('EventTarget.addEventListener: options.passive is not implemented.')
}
}
removeEventListener(type, listener) {
const events = _events.get(this)
if (events) {
const listeners = events[type]
if (listeners && listeners.length > 0) {
for (let i = listeners.length; i--; i > 0) {
if (listeners[i] === listener) {
listeners.splice(i, 1)
break
}
}
}
}
}
dispatchEvent(event = {}) {
if (typeof event.preventDefault !== 'function') {
event.preventDefault = () => {}
}
if (typeof event.stopPropagation !== 'function') {
event.stopPropagation = () => {}
}
const listeners = _events.get(this)[event.type]
if (listeners) {
for (let i = 0; i < listeners.length; i++) {
listeners[i](event)
}
}
}
dispatchTouchEvent(e = {}) {
const target = {
...this
}
const event = {
changedTouches: e.changedTouches.map(touch => new Touch(touch)),
touches: e.touches.map(touch => new Touch(touch)),
targetTouches: Array.prototype.slice.call(e.touches.map(touch => new Touch(touch))),
timeStamp: e.timeStamp,
target: target,
currentTarget: target,
type: e.type,
cancelBubble: false,
cancelable: false
}
this.dispatchEvent(event)
}
}