HackerNews JS(3)

ha·2022년 7월 28일
0

HackerNews JS

목록 보기
3/6

1.라우터 기능 추가
2.메인페이지, 상세페이지 주소 설정
3.페이지네이션

1.라우터

function router() {
  const routePath = location.hash;
  if (routePath === '') {
    newsFeed()
  } else if(routePath.indexOf('#/page/') >= 0 ){
    store.currentPage = Number(routePath.substr(7));
    newsFeed();
  }
  else {
    newsDetail();
  }
}
window.addEventListener('hashchange', router)
router();

2.메인페이지, 상세페이지

function newsFeed() {
  const newsFeed = getData(NEWS_URL);
  const newsList = [];

  newsList.push('<ul>');
  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>
    `);
  }
  newsList.push('</ul>');
  newsList.push(`
    <div>
      <a href="#/page/${store.currentPage - 1 === 0 ? 1 : store.currentPage-1}">이전페이지</a>
      <a href="#/page/${store.currentPage + 1 > newsFeed.length/10 ? store.currentPage : store.currentPage+1}">다음페이지</a>
    </div>
  `);
  container.innerHTML = newsList.join('');
}
function newsDetail() {
  const id = location.hash.substr(7)
  const newsContent = getData(CONTENT_URL.replace('@id', id))

  container.innerHTML = `
    <h1>${newsContent.title}</h1>
    <div>
      <a href="#/page/${store.currentPage}">목록으로</a>
    </div>
  `;
}

3.페이지네이션

const store = {
  currentPage: 1,
};

newsList.push(`
    <div>
      <a href="#/page/${store.currentPage - 1 === 0 ? 1 : store.currentPage-1}">이전페이지</a>
      <a href="#/page/${store.currentPage + 1 > newsFeed.length/10 ? store.currentPage : store.currentPage+1}">다음페이지</a>
    </div>
  `);

0개의 댓글