-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtoy-react.js
More file actions
65 lines (63 loc) · 1.62 KB
/
toy-react.js
File metadata and controls
65 lines (63 loc) · 1.62 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
class ElementWrapper{
constructor(type) {
this.root = document.createElement(type)
}
setAttribute(name, value) {
this.root.setAttribute(name, value)
}
appendChild(component) {
this.root.appendChild(component.root)
}
}
class TextWrapper{
constructor(content){
this.root = document.createTextNode(content)
}
}
export class Component{
constructor(){
this.props = Object.create(null)
this.children = []
this._root = null
}
setAttribute(name, value) {
this.props[name] = value
}
appendChild(component) {
this.children.push(component)
}
get root(){
if(!this._root) {
this._root = this.render().root
}
return this._root
}
}
export function createElement(type, attributes, ...children) {
let e ;
if(typeof type === 'string') {
e = new ElementWrapper(type)//document.createElement(type)
} else {
e = new type
}
for(let p in attributes) {
e.setAttribute(p, attributes[p])
}
let insertChildren = function(children) {
for(let child of children){
if(typeof child === 'string'){
child = new TextWrapper(child)//document.createTextNode(child)
}
if(typeof child === 'object' && child instanceof Array){
insertChildren(child)
} else {
e.appendChild(child)
}
}
}
insertChildren(children)
return e
}
export function render(component, parentElement) {
parentElement.appendChild(component.root)
}