exercise2.js
JavaScript/modules/module5-browser-apis/code-examples/lesson1/exercise2.js
// Exercise 2: Single Page Application Router
class SimpleRouter {
constructor() {
this.routes = new Map();
this.currentRoute = null;
this.setupRouter();
}
addRoute(path, handler) {
this.routes.set(path, handler);
}
setupRouter() {
// Handle initial route
this.handleRoute(window.location.pathname);
// Handle browser navigation
window.addEventListener('popstate', (event) => {
this.handleRoute(window.location.pathname);
});
}
navigate(path, state = {}) {
const handler = this.routes.get(path);
if (handler) {
history.pushState(state, '', path);
this.handleRoute(path);
} else {
console.error(`Route not found: ${path}`);
}
}
handleRoute(path) {
const handler = this.routes.get(path);
if (handler) {
this.currentRoute = path;
handler();
} else {
// Default route
this.navigate('/');
}
}
getCurrentRoute() {
return this.currentRoute;
}
}
// Usage
const router = new SimpleRouter();
router.addRoute('/', () => {
document.getElementById('content').innerHTML = '<h1>Home Page</h1>';
});
router.addRoute('/about', () => {
document.getElementById('content').innerHTML = '<h1>About Page</h1>';
});
router.addRoute('/contact', () => {
document.getElementById('content').innerHTML = '<h1>Contact Page</h1>';
});
// Navigation buttons
document.getElementById('homeBtn').addEventListener('click', () => router.navigate('/'));
document.getElementById('aboutBtn').addEventListener('click', () => router.navigate('/about'));
document.getElementById('contactBtn').addEventListener('click', () => router.navigate('/contact'));
관련 글
exercise1.js
exercise1.js — javascript source code from the JavaScript learning materials (JavaScript/modules/module1-foundations/code-examples/lesson1/exercise1.js).
글 읽기 →exercise2.js
exercise2.js — javascript source code from the JavaScript learning materials (JavaScript/modules/module1-foundations/code-examples/lesson1/exercise2.js).
글 읽기 →exercise3.js
exercise3.js — javascript source code from the JavaScript learning materials (JavaScript/modules/module1-foundations/code-examples/lesson1/exercise3.js).
글 읽기 →hello.js
hello.js — javascript source code from the JavaScript learning materials (JavaScript/modules/module1-foundations/code-examples/lesson1/hello.js).
글 읽기 →exercise1.js
exercise1.js — javascript source code from the JavaScript learning materials (JavaScript/modules/module1-foundations/code-examples/lesson2/exercise1.js).
글 읽기 →exercise2.js
exercise2.js — javascript source code from the JavaScript learning materials (JavaScript/modules/module1-foundations/code-examples/lesson2/exercise2.js).
글 읽기 →