Advertisement
Guest User

Untitled

a guest
Nov 18th, 2016
371
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. /**
  2. * Created by Kondoff on 17-Nov-16.
  3. */
  4. function attachEvents() {
  5. $('#btnLoad').click(loadContacts);
  6. $('#btnCreate').click(createContacts);
  7.  
  8. let baseUrl='https://kondoff-95d1e.firebaseio.com/phonebook';
  9.  
  10. function loadContacts() {
  11. $('#phonebook').empty();
  12. $.get(baseUrl + '.json')
  13. .then(displayContacts)
  14. .catch(displayError)
  15. }
  16.  
  17. function displayError(err) {
  18. $('#phonebook').html($('<li>Error</li>'))
  19. }
  20.  
  21. function displayContacts(contacts) {
  22. let keys=Object.keys(contacts);
  23. for (let key of keys){
  24. let contact=contacts[key];
  25. let text=contact.person +': '+ contact.phone + ' ';
  26. let textJSON=JSON.stringify(text);
  27. let li=$('<li>');
  28. li.text(text)
  29. li.appendTo($('#phonebook'));
  30. li.append($('<button> Delete</button>').click(function()
  31. {
  32. deleteContact(key)
  33. }))
  34. }
  35.  
  36. }
  37.  
  38. function createContacts() {
  39. let person=$('#person').val();
  40. let phone=$('#phone').val();
  41. let newContact={person,phone};
  42. let createRequest={
  43. method:"POST",
  44. url:baseUrl+'.json',
  45. data:JSON.stringify(newContact)
  46. };
  47.  
  48. $.ajax(createRequest)
  49. .then(loadContacts)
  50. .catch(displayError);
  51. $('#person').val('');
  52. $('#phone').val('');
  53. }
  54.  
  55.  
  56.  
  57. function deleteContact(key) {
  58. let delRequest={
  59. method:"DELETE",
  60. url: baseUrl + '/' + key + '.json'
  61. };
  62. $.ajax(delRequest)
  63. .then(loadContacts)
  64. .catch(displayError)
  65. }
  66.  
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement