-
Notifications
You must be signed in to change notification settings - Fork 0
/
document.createElement_.ts
104 lines (94 loc) · 3.25 KB
/
document.createElement_.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
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
const isIE7AndBelow = /MSIE (6|7)/.test(window.navigator.appVersion);
(document as Document & {
createElement_: typeof document.createElement;
}).createElement_ = window.addEventListener
? function (nodeName: keyof HTMLElementTagNameMap) {
const element = document.createElement(
nodeName
) as HTMLElementTagNameMap[keyof HTMLElementTagNameMap] & {
setAttribute_: (qualifiedName: string, value: string) => void;
removeAttribute_: (qualifiedName: string) => void;
};
element.setAttribute_ = element.setAttribute;
element.removeAttribute_ = element.removeAttribute;
return element;
}
: function (nodeName: keyof HTMLElementTagNameMap) {
const element = document.createElement(
nodeName
) as HTMLElementTagNameMap[keyof HTMLElementTagNameMap] & {
setAttribute_: (qualifiedName: string, value: string) => void;
removeAttribute_: (qualifiedName: string) => void;
attachEvent: (type: string, listener: unknown) => void;
detachEvent: (type: string, listener: unknown) => void;
};
const registry: unknown[][] = [];
element.addEventListener = function (
type: string,
listener: (
this: typeof element,
ev: HTMLElementEventMap[keyof HTMLElementEventMap]
) => any
) {
const target = this;
registry.unshift([
target,
type,
listener,
function (event: HTMLElementEventMap[keyof HTMLElementEventMap]) {
(event as {
currentTarget: EventTarget | null;
}).currentTarget = target;
event.preventDefault = function () {
event.returnValue = false;
};
event.stopPropagation = function () {
event.cancelBubble = true;
};
(event as { target: EventTarget | null }).target =
event.srcElement || target;
listener.call(target, event);
}
]);
this.attachEvent("on" + type, registry[0][3]);
};
element.removeEventListener = function (
type: string,
listener: (
this: typeof element,
ev: HTMLElementEventMap[keyof HTMLElementEventMap]
) => any
) {
for (let index = 0, register; (register = registry[index]); ++index) {
if (
register[0] == this &&
register[1] == type &&
register[2] == listener
) {
return this.detachEvent(
"on" + type,
registry.splice(index, 1)[0][3]
);
}
}
};
element.setAttribute_ = isIE7AndBelow
? function (name, value) {
if (name === "class") {
return element.setAttribute("className", value);
} else {
return element.setAttribute(name, value);
}
}
: element.setAttribute;
element.removeAttribute_ = isIE7AndBelow
? function (name) {
if (name === "class") {
return element.removeAttribute("className");
} else {
return element.removeAttribute(name);
}
}
: element.removeAttribute;
return element;
};