-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFinalScript.js
More file actions
100 lines (53 loc) · 2.41 KB
/
FinalScript.js
File metadata and controls
100 lines (53 loc) · 2.41 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
/** @jsx h */
// ^^^^ this tells a transpiler to inject calls to an `h()` function for each node.
const ITEMS = 'Abhay Bhavya Madhav'.split(' '); // Array of Names
// Creating a JS Function
function foo(items) {
// Returning a Vdom Tree or Object
return items.map(p => h("li", null, " ", p, " ")); // <-- can be multiline -> Sending Child Nodes
}
let vdom =
/*
We have a div inside we have a child node as <p> and <ul> which is converted into a Virtual Dom Tree via H()-> Hyperscript Generator
*/
h("div", { id: "div1" },
h("p", null , h("u" , null , h("b" , null , "Simple JSX Renderer"))),
h("ul", null, foo(ITEMS)));
/** @jsx h */
// Transpiling and making h function call using Babel
let newvdom = <div>Hey EveryOne <b>My Name is Abhay</b></div> ;
document.body.appendChild(render(newvdom));
// render() converts our "virtual DOM" (see below) to a real DOM Tree Structure Via using Simple Core JS Functions
let dom = render(vdom);
// append the new nodes somewhere:
document.body.appendChild(dom);
// Remember that "virtual DOM"? It's just JSON - each "VNode" is an object with 3 properties.
let json = JSON.stringify(vdom, null, ' ');
document.body.appendChild(render(h("div" , null , "Theese Vdom is nothing but Just a Json object with 3 Properties i.e - NodeName , attributes , ChildNodes")));
// The whole process (JSX -> VDOM -> DOM) in one step:
document.body.appendChild(
render(h("p", null, json)));
/** Render Virtual DOM to the real DOM */
function render (vnode) {
// strings converted to #text Node instead of HTML Element
if(vnode.split) return document.createTextNode(vnode);
// Creating a dom element
let Dom_Node = document.createElement(vnode.nodeName);
// making the attributes settled for the new node
let attributes = vnode.attributes || {};
// Iterating over all the keys in given Object
Object.keys(attributes).forEach((att)=>Dom_Node.setAttribute(att , attributes[att]));
// Reccursive Call
(vnode.children || []).forEach( c => Dom_Node.appendChild(render(c)));
return Dom_Node;
}
/** hyperscript generator, gets called by transpiled JSX to Create a Virtual Dom Structure*/
function h (
nodeName ,
attributes,
...args
){
const children = args.length ? [].concat(...args) : null ;
return {nodeName , attributes , children};
}
// WE WILL JUST INJECT THIS JS FILE INTO THE HTML FILE AND THINGS WILL BE RENDERED