Muscardinus

React Router 간단 구현 본문

FrontEnd/Basic Skills

React Router 간단 구현

Muscardinus 2022. 7. 3. 22:53
728x90
class Router {
  routes = [];
  notFoundCallback = () => {};

  addRoute(url, callback) {
    this.routes.push({ url, callback });
    return this;
  }

  checkRoute() {
    const currentRoute = this.routes.find(
      (route) => route.url === window.location.hash
    );

    if (!currentRoute) {
      this.notFoundCallback();
      return;
    }

    currentRoute.callback();
  }

  init() {
    window.addEventListener("hashchange", this.checkRoute.bind(this));
    if (!window.location.hash) {
      window.location.hash = "#/";
    }
    this.checkRoute();
  }

  setNotFound(callback) {
    this.notFoundCallback = callback;
    return this;
  }
}

 

document.addEventListener("DOMContentLoaded", () => {
  const router = new Router();
  const todoList = new TodoList();
  //예시 callback -> 해당 router에 해당하는 todoList 보여주기
  const routerCallback = (status) => () => {
    todoList.filterTodo(status);
    document.querySelector(
      `input[type='radio'][value='${status}']`
    ).checked = true;
  };
  router
    .addRoute("#/all", routerCallback("ALL"))
    .addRoute("#/todo", routerCallback("TODO"))
    .addRoute("#/done", routerCallback("DONE"))
    .setNotFound(routerCallback("ALL"))
    .init();
});
728x90

'FrontEnd > Basic Skills' 카테고리의 다른 글

Drag and Drop 라이브러리  (0) 2022.07.05
Checkbox  (0) 2022.03.21
Instant Search  (0) 2022.03.21
Tabs  (0) 2022.03.21
Carousel  (0) 2022.03.20
Comments