✍ 따뜻한 개발 공부
[Ajax] 템플릿을 사용하여 복잡한 코드를 가시화 시키기
따따시
2022. 8. 12. 12:39
const container = document.getElementById('root');
const ajax = new XMLHttpRequest();
const content = document.createElement('div');
const store = {
currentPage: 1,
};
function getData(url) {
ajax.open('GET', url, false);
ajax.send();
return JSON.parse(ajax.response);
}
function newsFeed() {
const newsFeed = getData(NEWS_URL);
const newsList = [];
// 템플릿은 쇠틀(무기를 찍어내는 틀) , 아래 코드에서 쇠틀 안에 쇳물(데이터)을 붓는 작업을 해주기
let template = `
<div>
<h1>해커 뉴스</h1>
<ul>
{{__news_feed__}}
</ul>
</div>
<a href="#/page/{{__prev_page__}}">이전 페이지</a>
<a href="#/page/{{__next_page__}}">다음 페이지</a>
</div>
</div>
`;
for(let i = (store.currentPage - 1) * 10; i < store.currentPage * 10; i++) {
newsList.push(`
<li>
<a href="#/show/${newsFeed[i].id}">
${newsFeed[i].title} (${newsFeed[i].comments_count})
</a>
</li>
`);
}
// 위에 만들어놓았던 template 에 데이터 부어주기
template =template.replace('{{__news_feed__}}',newsList.join(''));
template =template.replace('{{__prev_page__}}',store.currentPage > 1 ? store.currentPage -1 : 1);template =template.replace('{{__next_page__}}',store.currentPage + 1 );
container.innerHTML = template;
}
function newsDetail() {
const id = location.hash.substr(1); //# 값의 2번째 이후부터의 값들을 불러오는 것 (앞의 #을 제거했음)
const newsContent = getData(CONTENT_URL.replace('@id', id))
container.innerHTML = `
<h1>${newsContent.title}</h1>
<div>
<a href="#">목록으로</a>
</div>
`;
}
function router() {
const routePath = location.hash;
if (routePath === '') {
newsFeed(); //라우터가 아무것도 없으면 newsFeed를 보여주고
} else if (routePath.indexOf('#/page/') >= 0) { //routhPath 안에 '#/page/'라는 문자열이 들어가있는지 찾는 메소드 : indexOf
// indexOf는 찾고자하는 문자열이 있다면 0 이상의 위치값을 리턴하고, 없다면 -1을 리턴하는 함수다.
// 따라서 indexOf('#/page/') 값이 0보다 크다는 건 '#/page/' 문자열이 있다는 거즹
store.currentPage = Number(routePath.substr(7));
// store.currentPage = routePath.substr(7);
// 로 불러오면 오류가 난다.
// 왜냐면 substr은 '문자'로 불러온거라 이 불러온 문자열을 숫자로 바꿔주는 작업을 해야하기 때문
// routePath.substr(7)을 'Number()' 로 감싸주면 문자열이 숫자로 전환된다.
newsFeed();
} else {
newsDetail()
}
}
window.addEventListener('hashchange', router);
router();