-
Notifications
You must be signed in to change notification settings - Fork 4
/
script.js
96 lines (81 loc) · 2.28 KB
/
script.js
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
(function($){
$(document).ready(function(){
function sendRequest(method, url, data){
let xhr = new XMLHttpRequest();
let p = new Promise(function(resolve, reject){
xhr.onload = function() {
if(xhr.status === 200) {
resolve(JSON.parse(xhr.response));
} else {
reject (new Error("Wystąpił błąd")) ;
}
};
xhr.onerror = function() {
reject (new Error("Wystapił błąd"));
};
});
xhr.open(method, url);
if(data){
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify(data));
}else{
xhr.send();
}
return p;
};
let tasks =[];
function renderTodos(){
sendRequest("GET", "http://localhost:3000/todos")
.then(
resp => {
tasks = resp,
renderTasks(tasks)
},
err => $("#output").textContent = err.message
)
};
function renderTasks(tasks){
tasks.forEach(task => $("#output").append(taskTemplate(task)));
};
function taskTemplate(task){
let todo = $("<div class='todo'></div>");
todo.text(task.name);
return todo;
};
$('#output').on('click', '.todo', function(e) {
const taskName = e.target.textContent;
const task = tasks.find( t => t.name == taskName);
if(!task.completed){
task.completed = true;
sendRequest("PUT", "http://localhost:3000/todos"+"/"+task.id, task);
$(this).addClass("task-completed");
} else {
task.completed = false;
sendRequest("PUT", "http://localhost:3000/todos"+"/"+task.id, task);
$(this).removeClass("task-completed");
};
console.log(task);
});
renderTodos();
});
})(jQuery)