[실습1] 라우터? 화면처리기 만들기

이짜젠·2021년 9월 6일
0

구조구축

AS-IS

하나의 화면에 appendChild DOM API를 이용해 요소가 계속 추가 되는 방식
화면의 전환이안되고 계속 새로운 요소가 추가되어 보여진다.

// 뉴스목록화면
const ulEl = document.createElement("ul");
for (let i = 0; i < newsFeed.length; i++) {
  const divEl = document.createElement("div");

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

  ulEl.appendChild(divEl.firstElementChild);
}

containerEl.appendChild(ulEl);

// 뉴스상세화면
window.addEventListener("hashchange", function () {
  const id = location.hash.substr(1);

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

  contentEl.appendChild(titleEl);
});

containerEl.appendChild(contentEl);

TO-BE

innerHTML로 기존값을 덮어씀으로써, 기존화면을 날리고 새로운 화면으로 구성한다.
DOM API를 모두 덜어내는 부가적인 리팩토링효과도있다.

// 뉴스목록화면
newsList.push("<ul>");

for (let i = 0; i < newsFeed.length; i++) {
  newsList.push(`
    <li>
      <a href="#${newsFeed[i].id}">
        ${newsFeed[i].title}(${newsFeed[i].comments_count})
      </a>
    </li>
  `);
}

newsList.push("</ul>");

// 뉴스상세화면
window.addEventListener("hashchange", function () {
  const id = location.hash.substr(1);

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

  containerEl.innerHTML = `
    <h1>${newsContent.title}</h1>
    <div>
      <a href="#">목록으로</a>
    </div>
  `;
});

함수분리

글 내용화면은 이벤트리스너함수로 묶여있지만, 글 목록화면은 함수로 묶여있지 않다.
글 목록 화면 함수를 함수로 묶어주자.

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

  newsList.push("<ul>");

  for (let i = 0; i < newsFeed.length; i++) {
    newsList.push(`
      <li>
        <a href="#${newsFeed[i].id}">
          ${newsFeed[i].title}(${newsFeed[i].comments_count})
        </a>
      </li>
    `);
  }

  newsList.push("</ul>");
  containerEl.innerHTML = newsList.join("");
}

function newsDetail() {
  const id = location.hash.substr(1);
  const newsContent = getData(CONTENT_URL.replace("@id", id));

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

라우터 작성

function router() {
  const routePath = location.hash;

  if (routePath === "") {
    newsFeed();
  } else {
    newsDetail();
  }
}

window.addEventListener("hashchange", router);
profile
오늘 먹은 음식도 기억이 안납니다. 그래서 모든걸 기록합니다.

0개의 댓글