Advertisement
Guest User

Untitled

a guest
Aug 1st, 2017
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.80 KB | None | 0 0
  1. function attachEvents() {
  2. const kinveyAppId = "kid_S12g5Xa8W";
  3. const serviceUrl = "https://baas.kinvey.com/appdata/" + kinveyAppId;
  4. const kinveyUsername = "peter";
  5. const kinveyPassword = "p";
  6. const base64auth = btoa(kinveyUsername + ":" + kinveyPassword);
  7. const authHeaders = {"Authorization": "Basic " + base64auth};
  8.  
  9. $('#btnLoadPosts').click(loadPostsClick);
  10. // ---------------- Edited ----------------
  11. // ('#btnViewPosts').click(viewPostClick); to ('#btnViewPost').click(viewPostClick);
  12. // ID of button was wrong
  13. $('#btnViewPost').click(viewPostClick);
  14.  
  15.  
  16. function loadPostsClick() {
  17. let loadPostRequest = {
  18. method: "GET",
  19. url: serviceUrl + "/posts/",
  20. headers: authHeaders
  21. };
  22. $.ajax(loadPostRequest)
  23. .then(displayPosts)
  24. .catch(displayError)
  25. }
  26.  
  27. function displayPosts(posts) {
  28. $('#posts').empty();
  29. for (let post of posts) {
  30. $('#posts').append($('<option>').text(post.title).val(post._id))
  31. }
  32. }
  33.  
  34. function viewPostClick() {
  35. // ---------------- Edited selectedPostID----------------
  36. // $('#posts').val(); to $('#posts option:selected').val();
  37. // now the postID is only the ID of the selected option element
  38. let selectedPostID = $('#posts option:selected').val();
  39. if (!selectedPostID) {
  40. return;
  41. }
  42.  
  43. let requestPost = $.ajax({
  44. method: "GET",
  45. url: serviceUrl + "/posts/" + selectedPostID,
  46. headers: authHeaders
  47. });
  48. let requestComments = $.ajax({
  49. url: serviceUrl + `/comments/?query={"post_id":"${selectedPostID}"}`,
  50. headers: authHeaders
  51. });
  52.  
  53. Promise.all([requestPost, requestComments])
  54. .then(displayPostWithComments)
  55. .catch(displayError)
  56. }
  57.  
  58. function displayPostWithComments([post, comments]) {
  59. $('#post-title').text(post.title);
  60. $('#post-body').text(post.body);
  61. $('#post-comments').empty();
  62.  
  63. for (let comment of comments) {
  64. $('#post-comments').append($("<li>").text(comment.text))
  65. }
  66. }
  67.  
  68. function displayError(err) {
  69. let errDiv = $('<div>').text("Error: " + err.status + " (" + err.statusText + ")");
  70. $(document.body).prepend(errDiv);
  71. setTimeout(function () {
  72. $(errDiv).fadeOut(function () {
  73. $(errDiv).remove();
  74. })
  75. }, 3000)
  76. }
  77.  
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement