-
Notifications
You must be signed in to change notification settings - Fork 77
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[13팀 김도은] [Chapter 1-1] 프레임워크 없이 SPA 만들기 #15
Open
dosilv
wants to merge
8
commits into
hanghae-plus:main
Choose a base branch
from
dosilv:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
680c837
feat: 폴더구조 정리, 페이지 분리, 라우팅 구현
dosilv 669a9b0
feat: router 및 컴포넌트 구조 수정, userService 구현
dosilv 78aaeed
feat: 이벤트 위임, hashRouter 구현
dosilv ee51cb8
chore: 코드 정리
dosilv 6d8d0b3
fix: route
dosilv dcb24d3
feat: observer를 이용한 전역 store 구현, import 경로 정리
dosilv c1ad935
fix: 해시라우팅 시 nav 변하지 않는 오류 수정, store subscriber 중복 문제 수정
dosilv 343d631
feat: 미로그인 시 방어 로직, isLiked 상태 추가
dosilv File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
export { default as router } from "./router"; | ||
export { default as routes } from "./routes"; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
import Routes from "./routes"; | ||
import userService from "../features/UserService"; | ||
import { Store } from "../features"; | ||
|
||
const store = Store.getInstance(); | ||
|
||
export const historyRouter = (path) => { | ||
store.clearListeners(); | ||
|
||
const pathToGo = interceptor(path); | ||
|
||
history.pushState({}, "", pathToGo); | ||
|
||
const page = Routes[pathToGo] ?? Routes[404]; | ||
const { view, init } = page(); | ||
|
||
document.querySelector("#root").innerHTML = view; | ||
init(); | ||
}; | ||
|
||
export const hashRouter = (hash) => { | ||
store.clearListeners(); | ||
|
||
const path = hash.replace("#", ""); | ||
const pathToGo = interceptor(path); | ||
|
||
window.location.hash = pathToGo; | ||
|
||
const page = Routes[pathToGo] ?? Routes[404]; | ||
const { view, init } = page(); | ||
|
||
document.querySelector("#root").innerHTML = view; | ||
init(); | ||
}; | ||
|
||
const interceptor = (path) => { | ||
let redirectedPath; | ||
|
||
if (path === "/profile" && !userService.isLoggedIn()) { | ||
redirectedPath = "/login"; | ||
} | ||
|
||
if (path === "/login" && userService.isLoggedIn()) { | ||
redirectedPath = "/"; | ||
} | ||
|
||
return redirectedPath ?? path; | ||
}; | ||
|
||
const router = (path) => | ||
window.location.hash ? hashRouter(path) : historyRouter(path); | ||
|
||
export default router; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
import { ErrorPage, LoginPage, MainPage, ProfilePage } from "../pages"; | ||
|
||
const Routes = { | ||
"/": () => MainPage(), | ||
"/profile": () => ProfilePage(), | ||
"/login": () => LoginPage(), | ||
404: () => ErrorPage(), | ||
}; | ||
|
||
export default Routes; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
const Store = (function () { | ||
let instance; | ||
|
||
const createStore = (initState = {}) => { | ||
let state = initState; | ||
const listeners = new Set(); | ||
|
||
return { | ||
getState: () => state, | ||
|
||
setState: (updater) => { | ||
state = typeof updater === "function" ? updater(state) : updater; | ||
listeners.forEach((listener) => { | ||
listener(state); | ||
}); | ||
}, | ||
|
||
subscribe: (listener) => { | ||
listeners.add(listener); | ||
return () => listeners.delete(listener); | ||
}, | ||
|
||
clearListeners: () => { | ||
listeners.clear(); | ||
}, | ||
}; | ||
}; | ||
|
||
return { | ||
getInstance: (initState = {}) => { | ||
if (!instance) { | ||
instance = createStore(initState); | ||
} | ||
return instance; | ||
}, | ||
}; | ||
})(); | ||
|
||
export default Store; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
import { USER_KEY } from "../shared/const"; | ||
|
||
class UserService { | ||
isLoggedIn = () => !!this.getUser(); | ||
|
||
setUser = ({ username, email, bio }) => { | ||
if (email && !this.isValidEmail(email)) { | ||
alert("이메일 형식을 확인해주세요."); | ||
} | ||
localStorage.setItem(USER_KEY, JSON.stringify({ username, email, bio })); | ||
}; | ||
|
||
getUser = () => { | ||
return JSON.parse(localStorage.getItem(USER_KEY)); | ||
}; | ||
|
||
clearUser = () => { | ||
return localStorage.removeItem(USER_KEY); | ||
}; | ||
|
||
emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/; | ||
isValidEmail = (val) => this.emailRegex.test(val); | ||
} | ||
|
||
const userService = new UserService(); | ||
|
||
export default userService; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
export { default as UserService } from "./UserService"; | ||
export { default as Store } from "./Store"; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
import { router } from "./app"; | ||
import { Store } from "./features"; | ||
import { POST_LIST } from "./shared"; | ||
|
||
const initLoadedListener = () => { | ||
document.addEventListener("DOMContentLoaded", () => { | ||
const currentPath = window.location.hash || window.location.pathname; | ||
router(currentPath); | ||
}); | ||
}; | ||
|
||
const initPopListener = () => { | ||
window.addEventListener("popstate", () => { | ||
const currentPath = window.location.hash || window.location.pathname; | ||
router(currentPath); | ||
}); | ||
}; | ||
|
||
const initHashChangeListener = () => { | ||
window.addEventListener("hashchange", () => { | ||
const currentPath = window.location.hash || window.location.pathname; | ||
router(currentPath); | ||
}); | ||
}; | ||
|
||
export const initApp = () => { | ||
initPopListener(); | ||
initHashChangeListener(); | ||
initLoadedListener(); | ||
|
||
const store = Store.getInstance(); | ||
store.setState({ postList: POST_LIST }); | ||
}; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
라우터에 클린업 함수를 추가하셨네요! 이렇게 하면 불필요한 이벤트 리스너가 남지 않아 성능 개선이 도움이 될 거 같아요. 저도 참고하겠습니다👍🏻
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
사실 지금으로선 괜찮지만, 라우트를 변경해도 유지되어야 하는 subscriber가 있을 경우를 고려해서 다른 방식을 찾고 싶었는데... 현재 구조에선 찾지 못해서 이렇게 구현했어요ㅎ.ㅎ