Advertisement
EntropyStarRover

Rest 04. Messenger

Nov 9th, 2019
154
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function attachEvents() {
  2. let authorInp = document.getElementById("author");
  3. let contentInp = document.getElementById("content");
  4.  
  5. let sendBtn = document.getElementById("submit");
  6. let refreshBtn = document.getElementById("refresh");
  7.  
  8. let chatBox = document.getElementById("messages");
  9. console.log(chatBox)
  10.  
  11. sendBtn.addEventListener("click", function () {
  12. let authorName = authorInp.value;
  13. let msgText = contentInp.value;
  14. let msgObj = {
  15. author: authorName,
  16. content: msgText
  17. }
  18. console.log(msgObj)
  19.  
  20. fetch('https://rest-messanger.firebaseio.com/messanger.json', {
  21. method: 'post',
  22. headers: {
  23. 'Content-type': 'application/json'
  24. },
  25. body: JSON.stringify(msgObj),
  26. })
  27. contentInp.value="";
  28. })
  29.  
  30. refreshBtn.addEventListener("click", function () {
  31. fetch('https://rest-messanger.firebaseio.com/messanger.json')
  32. .then(res => res.json())
  33. .then(data => {
  34. let arrayResponse = Object.entries(data);
  35. arrayResponse.forEach(obj => {
  36. console.log(obj)
  37. let composedMessage = `${obj[1].author}: ${obj[1].content}`
  38. chatBox.textContent += `${composedMessage}\n`;
  39. authorInp.value="";
  40. contentInp.value="";
  41.  
  42. });
  43. })
  44. })
  45.  
  46. }
  47.  
  48. attachEvents();
Advertisement
RAW Paste Data Copied
Advertisement