Advertisement
Guest User

Untitled

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