Advertisement
boris-ivanov

ajax requests

Jul 24th, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. //import { todos } from './database.js';
  2. import { todoView } from './views.js';
  3. import { statics, todosContainer } from './common.js';
  4. import { deleteTodo, addTodo, toggleTodo } from './events.js';
  5. //let todos=[] // използва се за кеширани данни
  6. const populateTodos = (todos, container) => {
  7.  
  8. const $div = $(container);
  9. $div.empty();
  10. fetch('http://localhost:3000/todos')
  11. .then((res)=>res.json())
  12. .then((res)=>{res.forEach((todo) => todoView(todo, container));
  13. })
  14. };
  15.  
  16. (() => {
  17. let todos=[]
  18. // Initial populate
  19. populateTodos(todos, todosContainer);
  20.  
  21. // Attach events here
  22. deleteTodo((ev) => {
  23. const $target = $(ev.target);
  24. const todosList = todos.filter((todo) => todo.id !== +$target.attr('data-id'));
  25. let $targetid=+$target.attr('data-id');
  26. fetch(`http://localhost:3000/todos`+'/'+$targetid, {
  27. method: 'DELETE',
  28. }).then((res) => {
  29. populateTodos(todosList, todosContainer);
  30. // What you should do here?
  31. }).catch((err) => alert(err.message));
  32. });
  33.  
  34. addTodo((ev) => {
  35. const $text = $('#todo-text')
  36. const $date = $('#todo-date')
  37.  
  38. if ($($date).val()) {
  39. statics.id++;
  40. fetch(`http://localhost:3000/todos`, {
  41. method: 'POST',
  42. headers: {
  43. 'Content-Type': 'application/json'
  44. },
  45. body: JSON.stringify({ id:statics.id, name:$text.val() ,due: $date.val(),isDone:false, isDeleted:false })
  46. }).then((res) => {
  47. populateTodos(todos, todosContainer);
  48. $text.val('');
  49. $date.val('');
  50. res.json()
  51. }).catch((err) => alert(err.message))
  52. } else {
  53. alert('Invalid date');
  54. }
  55. });
  56.  
  57. toggleTodo((ev) => {
  58. const $target = $(ev.target);
  59.  
  60. const todosList = todos.map((todo) => {
  61. if (todo.id === +$target.attr('data-check-id')) {
  62. todo.isDone = !$target.attr('checked');
  63. }
  64.  
  65. return todo;
  66. });
  67.  
  68. populateTodos(todosList, todosContainer);
  69. });
  70. })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement