Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function attachEvents() {
- const BASE_URL_POSTS = 'http://localhost:3030/jsonstore/blog/posts/';
- const BASE_URL_COMMENTS = 'http://localhost:3030/jsonstore/blog/comments/';
- const btnLoadPosts = document.getElementById('btnLoadPosts');
- const viewBtn = document.getElementById('btnViewPost');
- const optionPosts = document.getElementById('posts');
- const postTitle = document.getElementById('post-title');
- const postBody = document.getElementById('post-body');
- const commentsBody = document.getElementById('post-comments');
- btnLoadPosts.addEventListener('click', loadPostHandler);
- viewBtn.addEventListener('click', loadCommentHandler);
- let posts = null;
- let comments = null;
- async function loadPostHandler() {
- const response = await fetch(BASE_URL_POSTS);
- posts = await response.json();
- for (const [_key, post] of Object.entries(posts)) {
- createElement('option', post.title, optionPosts, '', '', {value: post.id});
- }
- }
- async function loadCommentHandler(e) {
- const selected = e.currentTarget.previousElementSibling.value;
- const responseComments = await fetch(BASE_URL_COMMENTS);
- comments = await responseComments.json();
- console.log(selected);
- const post = Object.entries(posts).find(el => selected === el[0]);
- const [_postID, postData] = post;
- const comment = Object.entries(comments).filter(el => el[1].postId === selected);
- console.log(comment);
- postTitle.textContent = postData.title;
- postBody.textContent = postData.body;
- commentsBody.innerHTML = '';
- comment.forEach(el => createElement('li', el[1].text, commentsBody, el[0]));
- }
- function createElement(type, content, parentNode, id, classes, attributes) {
- const htmlElement = document.createElement(type);
- if (content && type !== 'input') {
- htmlElement.textContent = content;
- }
- if (content && type === 'input') {
- htmlElement.value = content;
- }
- if (id) {
- htmlElement.id = id;
- }
- if (classes) {
- htmlElement.classList.add(...classes);
- }
- if (parentNode) {
- parentNode.appendChild(htmlElement);
- }
- if (attributes) {
- for (const key in attributes) {
- htmlElement.setAttribute(key, attributes[key]);
- }
- }
- return htmlElement;
- }
- }
- attachEvents();
Advertisement
Add Comment
Please, Sign In to add comment