Skip to content

Commit

Permalink
Merge pull request #3 from f-lab-edu/refactor/separation-js
Browse files Browse the repository at this point in the history
Refactor/separation js
  • Loading branch information
nemo0824 authored Jan 3, 2025
2 parents b83a613 + c439396 commit 72f5f74
Show file tree
Hide file tree
Showing 7 changed files with 106 additions and 78 deletions.
76 changes: 11 additions & 65 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,68 +1,14 @@
// 데이터 가져오기
let data = [];

async function fetchData() {
const response = await fetch('/posts.json');
data = await response.json();
renderPage('/');
}

function renderPage(route) {
const app = document.getElementById('app');
let filteredData;
// 라우트가 메인페이지일떄
if (route === '/') {
filteredData = data;
app.innerHTML = `
<ul>
${filteredData.map((item) => `<li><a href="/detail/${item.id}" data-link>${item.title}</a></li>`).join('')}
</ul>
`;
// 라우트가 detail일떄
} else if (route.startsWith('/detail')) {
const id = route.split('/')[2];
const item = data.find((item) => item.id == id);
// 라우트가 detail 일치하는 id 가있을떄
if (item) {
app.innerHTML = `
<h3>${item.title}</h3>
<h3>${item.content}</h3>
`;
}
// 라우트가 develop, design일때
} else {
filteredData = data.filter(
(item) => item.category === route.replace('/', '')
);
app.innerHTML = `
<ul>
${filteredData.map((item) => `<li><a href="/detail/${item.id}" data-link>${item.title}</a></li>`).join('')}
</ul>
`;
import { setupRouter } from './router.js';
import { setNavEvent } from './navbar.js';

// 초기화함수
async function initApp() {
try {
setNavEvent();
setupRouter();
} catch (error) {
console.error('초기화 에러', error);
}
}

function navigate(url, state = {}) {
history.pushState(state, null, url);
renderPage(url);
}

document.addEventListener('click', (e) => {
if (e.target.matches('[data-link]')) {
e.preventDefault();
const url = e.target.getAttribute('href');
console.log('url', url);
const state = { id: url.split('/')[2] };
navigate(url, state);
}
});

window.addEventListener('popstate', (e) => {
console.log('e', e);
if (e.state) {
console.log('e.state', e.state);
renderPage(location.pathname);
}
});

fetchData();
initApp();
14 changes: 14 additions & 0 deletions dataservice.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
export async function fetchAllData() {
const response = await fetch('/posts.json');
return await response.json();
}

export async function fetchCategoryData(category) {
const response = await fetchAllData();
return response.filter((item) => item.category === category);
}

export async function fetchDetailData(id) {
const response = await fetchAllData();
return response.find((item) => item.id == id);
}
22 changes: 10 additions & 12 deletions index.html
Original file line number Diff line number Diff line change
@@ -1,25 +1,23 @@
<!DOCTYPE html>
<html lang="en">
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SPA-Project main</title>
<link rel="stylesheet" href="./style.css">
<script src="./app.js" defer type="module"></script>
</head>
<body>
<!-- 라우팅 history API 기반 라우팅 -->
<!-- 상태관리 -->
<!-- DOM 조작 및 렌더링 -->
<!-- 성능최적화 -->
<!-- tab 네비게이션 -->
<nav>
<a href="/" data-link>전체</a>
<a href="/develop" data-link>개발</a>
<a href="/design" data-link>디자인</a>
</nav>
<!-- 안쪽에 app 안에서 만들기 / 고정된걸 해결할수있는방법이있을수도있음 -->
<header>
<nav id="navbar">
<a href="/" data-link>전체</a>
<a href="/develop" data-link>개발</a>
<a href="/design" data-link>디자인</a>
</nav>
</header>
<div id="app">

</div>
<script src="./app.js"></script>
</body>
</html>
14 changes: 14 additions & 0 deletions navbar.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
export function setNavEvent() {
document.addEventListener('click', (e) => {
if (e.target.tagName === 'A' && e.target.hasAttribute('data-link')) {
e.preventDefault();
const url = e.target.getAttribute('href');
navigate(url);
}
});

function navigate(url) {
history.pushState(null, null, url);
window.dispatchEvent(new PopStateEvent('popstate'));
}
}
2 changes: 1 addition & 1 deletion posts.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@
{ "id": 4, "category": "design", "title": "Figma 사용법", "content": "Figma 사용법" },
{ "id": 5, "category": "develop", "title": "프로젝트 계획 수립", "content": "프로젝트 계획 수립"},
{ "id": 6, "category": "develop", "title": "협업 도구 소개" , "content": "협업 도구 소개"}
]
]
45 changes: 45 additions & 0 deletions router.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import {
fetchCategoryData,
fetchDetailData,
fetchAllData,
} from './dataservice.js';

async function renderPage(route) {
const app = document.getElementById('app');
let content = '';

if (route === '/') {
// 전체 페이지
const data = await fetchAllData(); // 전체 데이터 요청
content = `
<ul>
${data.map((item) => `<li><a href="/detail/${item.id}" data-link>${item.title}</a></li>`).join('')}
</ul>
`;
} else if (route.startsWith('/develop') || route.startsWith('/design')) {
// 카테고리 페이지
const category = route.replace('/', '');
const data = await fetchCategoryData(category);
content = `
<ul>
${data.map((item) => `<li><a href="/detail/${item.id}" data-link>${item.title}</a></li>`).join('')}
</ul>
`;
} else if (route.startsWith('/detail/')) {
// 상세 페이지
const id = route.split('/')[2];
console.log('id', id);
const item = await fetchDetailData(id);
content = `<h3>${item.title}</h3><p>${item.content}</p>`;
}

app.innerHTML = content;
}

export function setupRouter() {
renderPage(location.pathname);

window.addEventListener('popstate', () => {
renderPage(location.pathname);
});
}
11 changes: 11 additions & 0 deletions settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"liveServer.settings.root": "/",
"liveServer.settings.port": 8080,
"liveServer.settings.rewriteRules": [
{
"source": ".*",
"destination": "/index.html"
}
]
}

0 comments on commit 72f5f74

Please sign in to comment.