Skip to content

Commit

Permalink
Feat: 프레임워크 없이 SPA 만들기 | 심화 과제
Browse files Browse the repository at this point in the history
  • Loading branch information
Suyeon-B committed Dec 19, 2024
1 parent fd54d47 commit a37c2f8
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 5 deletions.
21 changes: 17 additions & 4 deletions src/components/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,20 @@ import { render404 } from "@/pages/not-found";
import { renderProfile } from "@/pages/profile";

class Router {
constructor(routes = {}) {
constructor(routes = {}, { mode = "history" }) {
this.routes = routes;
this.currentRoute = "";
this.mode = mode;
}

initialize() {
this.addEventListeners();
this.navigateTo(location.pathname || "/");

if (this.mode === "history") {
this.navigateTo(location.pathname);
} else if (this.mode === "hash") {
this.navigateTo(location.hash || "/");
}
}

addEventListeners() {
Expand All @@ -26,13 +32,20 @@ class Router {
window.addEventListener("popstate", () => {
this.navigateTo(location.pathname, false);
});
window.addEventListener("hashchange", () => {
this.navigateTo(location.hash.slice(1), false);
});
}

navigateTo(path, pushState = true) {
if (this.routes[path]) {
this.currentRoute = path;
if (pushState) {
history.pushState({}, "", path);
if (this.mode === "hash") {
location.hash = path;
} else if (this.mode === "history") {
history.pushState({}, "", path);
}
}
this.render();
} else {
Expand All @@ -56,4 +69,4 @@ const routes = {
"/404": render404,
};

export const router = new Router(routes);
export const router = new Router(routes, { mode: "history" });
7 changes: 6 additions & 1 deletion src/pages/login.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import { setUser } from "@/state/handle-state";
import { setUser, getUser } from "@/state/handle-state";
import { router } from "@/components/router";

export const renderLogin = () => {
if (getUser() !== null) {
router.navigateTo("/");
return;
}

document.body.innerHTML = LoginPage();
};

Expand Down
6 changes: 6 additions & 0 deletions src/pages/profile.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
import { setUser, getUser } from "@/state/handle-state";
import { Layout } from "@/components/layout/layout";
import { router } from "@/components/router";

export const renderProfile = () => {
if (getUser() === null) {
router.navigateTo("/login");
return;
}

document.body.innerHTML = ProfilePage();
};

Expand Down

0 comments on commit a37c2f8

Please sign in to comment.