forked from kelly422/Frontend-01-Template
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreateElement.js
More file actions
104 lines (83 loc) · 2 KB
/
Copy pathcreateElement.js
File metadata and controls
104 lines (83 loc) · 2 KB
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
import {enableGesture} from './week16/5_carouselWithLifecycle/gesture';
export function createElement(comp, attributes, ...children) {
// console.log(arguments);
// // debugger;
let ele;
if (typeof comp === 'string') {
ele = new Wrapper(comp);
} else {
ele = new comp({
initData: {}
});
}
for(let name in attributes) {
// ele[name] = attributes[name]; // attribute 和 property 是同一个
ele.setAttribute(name, attributes[name])
}
let visit = children => {
for (let child of children) {
if (typeof child === 'object' && child instanceof Array) {
visit(child);
continue;
}
if (typeof child === 'string') {
child = new TextNode(child);
}
ele.appendChild(child); // 添加 children 的方法一
// ele.children.push(child) // 方法二
}
};
visit(children);
return ele;
}
export class Wrapper {
constructor(type) {
this.children = [];
this.root = document.createElement(type)
}
setAttribute(name, value) { // attribute
// console.log('MyComponent::setAttribute', name, value);
this.root.setAttribute(name, value);
if(name.match(/^on([\s\S]+)$/)) {
this.addEventListener(RegExp.$1.replace(/[\s\S]/, c => c.toLowerCase()), value)
}
if(name === 'enableGesture') {
enableGesture(this.root)
}
}
getAttribute(name) {
return this.root.getAttribute(name)
}
get classList() {
return this.root.classList;
}
set innerText(text) {
return this.root.innerText = text;
}
appendChild(child) { // 添加children 的方法一
this.children.push(child)
}
addEventListener() {
this.root.addEventListener(...arguments)
}
get style() {
return this.root.style;
}
mountTo(parent) {
parent.appendChild(this.root);
for (let child of this.children) {
child.mountTo(this.root)
}
}
}
export class TextNode {
constructor(text) {
this.root = document.createTextNode(text)
}
mountTo(parent) {
parent.appendChild(this.root)
}
getAttribute(name) {
return
}
}