추가 개선:

 

변수 = 데이터를 담는 그릇

객체 = 변수 여러개를 담을 수 있는 그릇

함수 = 코드를 담을 수 있는 그릇

 

: 리팩토링

const container = document.querySelector('#root');
const ajax = new XMLHttpRequest();
const content = document.createElement('div');
const NEWS_URL = 'https://api.hnpwa.com/v0/news/1.json'
const CONTENT_URL = 'https://api.hnpwa.com/v0/item/@id.json';

function getData(url){
    
    ajax.open('GET', url, false); // method, Url, async
    ajax.send();

    return JSON.parse(ajax.response);
}

const newsFeed = getData(NEWS_URL)
const ul = document.createElement('ul');

window.addEventListener('hashchange', function(){
    const id = location.hash.substring(1);

    const newsContent = getData(CONTENT_URL.replace('@id', id));
    const title = document.createElement('h1');

    title.innerHTML = newsContent.title;

    content.appendChild(title);    
});

for(let i=0; i<newsFeed.length; i++){
    const div = document.createElement('div');    

    div.innerHTML = `
    <li>
        <a href="#${newsFeed[i].id}">
            ${newsFeed[i].title} (${newsFeed[i].comments_count})
        </a>
    </li>
    `;    
    
    ul.appendChild(div.firstElementChild);
}

container.appendChild(ul);
container.appendChild(content);

기존의 구조를 변경했다. ajax를 통해서 해커뉴스 서버의 데이터를 받아오는 방식을 특정한 곳에서나 여러번 사용 가능하도록 함수로 바꿨다. ajax나 fetch, axios 등의 서버에서 데이터를 가져오는 기능은 이벤트리스너 함수처럼 비동기로 처리해야 하지만 현재는 강의의 진행에따라 동기적인 방식으로 처리한다.

 

 

https://bit.ly/37BpXiC

 

패스트캠퍼스 [직장인 실무교육]

프로그래밍, 영상편집, UX/UI, 마케팅, 데이터 분석, 엑셀강의, The RED, 국비지원, 기업교육, 서비스 제공.

fastcampus.co.kr

 

본 포스팅은 패스트캠퍼스 환급 챌린지 참여를 위해 작성되었습니다.

 

#패스트캠퍼스 #패캠챌린지 #직장인인강 #직장인자기계발 #패스트캠퍼스후기 #김민태의프론트엔드아카데미:제1강JavaScript&TypeScriptEssential

'study' 카테고리의 다른 글

패스트캠퍼스 챌린지 11일차  (0) 2022.02.03
패스트캠퍼스 챌린지 10일차  (0) 2022.02.02
패스트캠퍼스 챌린지 8일차  (0) 2022.01.31
패스트캠퍼스 챌린지 7일차  (0) 2022.01.30
패스트캠퍼스 챌린지 6일차  (0) 2022.01.29

+ Recent posts