[JAVASCRIPT] Router & Component

CUBE·2023년 11월 12일
0

JAVASCRIPT 이해하기

목록 보기
3/8

Component화


DOM 접촉을 통해 DOM 내부에 자식 요소를 추가한다.
function func(data){
 const ele = document.createElement("div");
  ele.textContent = data;
  // ....
  return element
}

let appEle = documnet.getElementById("main");
const funcCompo = func("하하하");
appEle.appendChild(funcCompo)

Router화


container 객체에는 app 이라는 DOM에 접촉한다. home 에 element 를 추가하고, 내부에 TextNode를 생성한다. container에는 새로운 문장을 추가하고 container에 home을 자식요소로 등록한다. 첫번째 router 페이지 구성 요소는 그런식으로 되어있다.
// index.js 
var container = document.querySelector("app");

const pages = {
  home: () => {
    var home = document.createElement("div");
    let newContent = document.createTextnode("...");
    container.innerText = "Hello World"
    container.appendChild(home);
  	},
  oper: () => {
  	container.innerText = "operation";
  }
}

const router = createRouter();

router
  .addRoute("#/", pages.home)
  .addRoute("#/oper", pages.oper)
  .start();

createRouter에는 addRoute를 통해 router 경로를 push하는 메소드를 담고 있다. addRoute 메서드는 fragment, component를 인자로 갖고 있어, 인자를 routes로 넣어준다. createRouter가 실행이 될 떄 마다
router페이지를 check 하는 함수를 생성한 뒤 routes 내부에 find해서 fragment 인자와 window.locatino.hash 값과 동일한 해시값을 가진 구성요소를 찾아 낸다. 만약에 일치하는 구성 요소를 찾고 나면 페이지 이동을 보여주기 위해 내부에 뭐가 담겼는지 찾게 된다.

// router.js
export default function createRouter() {
  const routes = []; // 애플리케이션의 경로 목록들을 담을 배열이다. 클로저를 이용하여 데이터를 추가한다.

  const router = {
    // 라우터 기능 1. 애플리케이션의 경로 목록들을 저장한다.
    addRoute(fragment, component) {
      routes.push({fragment, component});
      return this;
    },
    // 라우터 기능 2. 현재 URL이 변경되면 페이지 콘텐츠를 해당 URL에 매핑된 구성 요소로 교체한다.
    start() {
      // routes 배열에서 현재 브라우저 hash값과 동일한 해시값을 가진 구성 요소를 찾는다.
      const checkRoutes = () => {
        const currentRoute = routes.find(route => route.fragment === window.location.hash);
        currentRoute.component(); // 페이지 이동을 보여주기 위해 innerText를 변경하는 메서드
      }
      window.addEventListener('hashchange', checkRoutes); // 브라우저에서 hash값이 바뀔때 발생하는 이벤트.
      checkRoutes();

    }
  };

  return router;
}
profile
엄마이오빠이상해

0개의 댓글