Advertisement
Guest User

Untitled

a guest
Aug 1st, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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.     $('#btnViewPosts').click(viewPostClick);
  11.  
  12.  
  13.     function loadPostsClick() {
  14.         let loadPostRequest = {
  15.             method: "GET",
  16.             url: serviceUrl + "/posts/",
  17.             headers: authHeaders
  18.         }
  19.         $.ajax(loadPostRequest)
  20.             .then(displayPosts)
  21.             .catch(displayError)
  22.     };
  23.     function displayPosts(posts) {
  24.         $('#posts').empty();
  25.         for (let post of posts) {
  26.             $('#posts').append($('<option>').text(post.title).val(post._id))
  27.         }
  28.     }
  29.     function viewPostClick() {
  30.       let selectedPostID = $('#posts').val();
  31.         if (!selectedPostID) {
  32.             return;
  33.         }
  34.  
  35.         let requestPost = $.ajax({
  36.             method: "GET",
  37.             url: serviceUrl + "/posts/" + selectedPostID,
  38.             headers: authHeaders
  39.         });
  40.         let requestComments = $.ajax({
  41.             url: serviceUrl + `/comments/?query={"post_id":"${selectedPostID}"}`,
  42.             headers: authHeaders });
  43.  
  44.         Promise.all([requestPost, requestComments])
  45.             .then(displayPostWithComments)
  46.             .catch(displayError)
  47.         }
  48.  
  49.         function displayPostWithComments([post, comments]) {
  50.             $('#post-title').text(post.title);
  51.             $('#post-body').text(post.body);
  52.             $('#post-comments').empty();
  53.  
  54.             for (let comment of comments) {
  55.                 $('#post-comments').append($("<li>").text(comment.text))
  56.             }
  57.         }
  58.  
  59.     function displayError(err) {
  60.         let errDiv = $('<div>').text("Error: " + err.status + " (" + err.statusText + ")");
  61.         $(document.body).prepend(errDiv);
  62.         setTimeout(function () {
  63.             $(errDiv).fadeOut(function () {
  64.                 $(errDiv).remove();
  65.             })
  66.         }, 3000)
  67.     }
  68.  
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement