-
Notifications
You must be signed in to change notification settings - Fork 0
/
example-todo.html
74 lines (66 loc) · 2.09 KB
/
example-todo.html
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
<!DOCTYPE HTML>
<html>
<head>
<script src="sugar.js"></script>
</head>
<body>
<div>
<h1>Todo list</h1>
<input id="input" type="text" placeholder="Thing to do" />
<button id="addBtn">Add</button>
<ul id="todos"></ul>
</div>
<script>
sugar(() => {
var ENDPOINT = 'api/todos'
var input = document.getElementById("input")
var addBtn = document.getElementById("addBtn")
var todoList = document.getElementById("todos")
addBtn.addEventListener('click', addTodo)
renderTodoList()
function renderTodoList() {
return fetch(ENDPOINT)
.then(response => response.json())
.then(todos => {
todoList.innerHTML = ""
for (const todo of todos) {
renderTodo(todo.id, todo.text)
}
})
}
function renderTodo(id, text) {
var li = document.createElement("li")
li.appendChild(document.createTextNode(text))
li.onclick = () => {
deleteTodo(id)
}
todoList.appendChild(li)
}
function addTodo() {
if (input.value.trim() === "") {
return
}
fetch(ENDPOINT, {
method: 'POST',
body: JSON.stringify({
"text": input.value
})
})
.then(response => response.json())
.then(todo => {
input.value = ""
renderTodo(todo.id, todo.text)
})
}
function deleteTodo(id) {
fetch(ENDPOINT+'/'+id, {
method: 'DELETE'
})
.then(response => {
renderTodoList()
})
}
})
</script>
</body>
</html>