Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function attachEvents() {
- const body = document.querySelector('body');
- body.addEventListener('click', (e) => service(e));
- async function service(e) {
- let url = `http://localhost:3030/jsonstore/phonebook`
- if (e.target.textContent === 'Load') {
- await load(url);
- } else if (e.target.textContent === 'Delete') {
- await deleteIt(url, e);
- } else if (e.target.textContent === 'Create') {
- await create(url)
- }
- }
- async function create(url) {
- let person = document.querySelector('#person')
- let phone = document.querySelector('#phone')
- const response = await fetch(url, {
- method: 'post',
- headers: {'Content-type': 'application/json'},
- body: JSON.stringify({person: person.value, phone: phone.value})
- })
- await response.json();
- person.value = "";
- phone.value = "";
- await load(url)
- }
- async function deleteIt(url, e) {
- let contactId = e.target.parentNode.id;
- const response = await fetch(url + `/${contactId}`, {
- method: 'delete'
- });
- await response.json();
- await load(url);
- }
- async function load(url) {
- const result = await fetch(url)
- const data = await result.json();
- const ul = document.querySelector('#phonebook')
- ul.innerHTML = "";
- Object.values(data).forEach(p => {
- let li = factory('li', `${p.person}: ${p.phone}`, undefined, 'id', `${p._id}`)
- let deleteBtn = factory('button', 'Delete')
- li.appendChild(deleteBtn);
- ul.appendChild(li)
- })
- }
- function factory(type, content, className, attribute, attributeValue) {
- const result = document.createElement(type);
- result.textContent = content;
- if (className) {
- result.classList.add(className)
- }
- if (attribute) {
- result.setAttribute(attribute, attributeValue)
- }
- return result;
- }
- }
- attachEvents();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement