Advertisement
petur_stoqnov

Untitled

Mar 6th, 2021
779
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function attachEvents() {
  2.     const body = document.querySelector('body');
  3.     body.addEventListener('click', (e) => service(e));
  4.  
  5.     async function service(e) {
  6.         let url = `http://localhost:3030/jsonstore/phonebook`
  7.         if (e.target.textContent === 'Load') {
  8.             await load(url);
  9.         } else if (e.target.textContent === 'Delete') {
  10.             await deleteIt(url, e);
  11.         } else if (e.target.textContent === 'Create') {
  12.             await create(url)
  13.         }
  14.     }
  15.  
  16.     async function create(url) {
  17.         let person = document.querySelector('#person')
  18.         let phone = document.querySelector('#phone')
  19.         const response = await fetch(url, {
  20.             method: 'post',
  21.             headers: {'Content-type': 'application/json'},
  22.             body: JSON.stringify({person: person.value, phone: phone.value})
  23.         })
  24.         await response.json();
  25.         person.value = "";
  26.         phone.value = "";
  27.         await load(url)
  28.     }
  29.  
  30.     async function deleteIt(url, e) {
  31.         let contactId = e.target.parentNode.id;
  32.         const response = await fetch(url + `/${contactId}`, {
  33.             method: 'delete'
  34.         });
  35.         await response.json();
  36.         await load(url);
  37.     }
  38.  
  39.     async function load(url) {
  40.         const result = await fetch(url)
  41.         const data = await result.json();
  42.         const ul = document.querySelector('#phonebook')
  43.         ul.innerHTML = "";
  44.         Object.values(data).forEach(p => {
  45.             let li = factory('li', `${p.person}: ${p.phone}`, undefined, 'id', `${p._id}`)
  46.             let deleteBtn = factory('button', 'Delete')
  47.             li.appendChild(deleteBtn);
  48.             ul.appendChild(li)
  49.         })
  50.     }
  51.  
  52.     function factory(type, content, className, attribute, attributeValue) {
  53.         const result = document.createElement(type);
  54.         result.textContent = content;
  55.         if (className) {
  56.             result.classList.add(className)
  57.         }
  58.         if (attribute) {
  59.             result.setAttribute(attribute, attributeValue)
  60.         }
  61.         return result;
  62.     }
  63. }
  64.  
  65. attachEvents();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement