1
1
2
2
const http = new XMLHttpRequest ( ) ;
3
3
4
+ const tbody = document . querySelector ( "tbody#tasks" ) ;
5
+ const template = document . querySelector ( "#todoRow" ) ;
6
+ const titleInput = document . querySelector ( "#title" ) ;
7
+ const orderInput = document . querySelector ( "#order" ) ;
8
+
4
9
function httpSend ( method , url , body , callback ) {
5
10
http . open ( method , url ) ;
6
11
http . setRequestHeader ( 'Content-type' , 'application/json' ) ;
@@ -16,33 +21,41 @@ function httpPost(url, body, callback) {
16
21
httpSend ( 'POST' , url , body , callback ) ;
17
22
}
18
23
24
+ function addTask ( task ) {
25
+ const clone = template . content . cloneNode ( true ) ;
26
+ const td = clone . querySelectorAll ( "td" ) ;
27
+ const input = clone . querySelectorAll ( "input" ) ;
28
+ td [ 0 ] . textContent = task . title ;
29
+ td [ 1 ] . textContent = task . order ;
30
+ input . checked = task . completed ;
31
+ tbody . appendChild ( clone ) ;
32
+ }
33
+
19
34
function add ( ) {
20
- let body = { title : 'a' , order : 0 } ;
35
+ const body = {
36
+ title : titleInput . value ,
37
+ order : orderInput . valueAsNumber
38
+ } ;
39
+
21
40
httpPost ( '/tasks' , body , ( ) => {
41
+ titleInput . value = "" ;
42
+ orderInput . value = 0 ;
22
43
23
- console . log ( http . responseText )
44
+ addTask ( JSON . parse ( http . responseText ) ) ;
24
45
} ) ;
25
46
}
26
47
27
48
function main ( ) {
28
- const tbody = document . querySelector ( "tbody#tasks" ) ;
29
- const template = document . querySelector ( "#todoRow" ) ;
30
49
31
50
httpGet ( '/tasks' , null , ( ) => {
32
- let response = JSON . parse ( http . responseText ) ;
33
- for ( const tr of tbody . children ) {
51
+ for ( const tr of tbody . children )
34
52
tr . remove ( ) ;
35
- }
36
53
37
- for ( const task of response ) {
38
- const clone = template . content . cloneNode ( true ) ;
39
- let td = clone . querySelectorAll ( "td" ) ;
40
- td [ 0 ] . textContent = task . title ;
41
- td [ 1 ] . textContent = task . order ;
42
- tbody . appendChild ( clone ) ;
43
- }
54
+ const response = JSON . parse ( http . responseText ) ;
55
+ for ( const task of response )
56
+ addTask ( task ) ;
44
57
45
- console . log ( http . responseText )
58
+ console . log ( http . responseText ) ;
46
59
} ) ;
47
60
}
48
61
0 commit comments