Now.js Framework Documentation

Now.js Framework Documentation

RouterManager

TH 15 Dec 2025 08:52

RouterManager

ภาพรวม

RouterManager คือระบบ client-side routing ใน Now.js Framework สำหรับ SPA (Single Page Application)

ใช้เมื่อ:

  • ต้องการ SPA routing
  • ต้องการ page navigation without reload
  • ต้องการ route guards
  • ต้องการ dynamic routes

ทำไมต้องใช้:

  • ✅ Hash and History mode
  • ✅ Route parameters
  • ✅ Navigation guards
  • ✅ Lazy loading
  • ✅ Auto template loading
  • ✅ Scroll restoration

การใช้งานพื้นฐาน

Initialization

await RouterManager.init({
  mode: 'history',  // or 'hash'
  routes: [
    { path: '/', template: '/pages/home.html' },
    { path: '/about', template: '/pages/about.html' },
    { path: '/users/:id', template: '/pages/user.html' }
  ]
});
<!-- Regular links work automatically -->
<a href="/about">About</a>
<a href="/users/123">User Profile</a>

<!-- Programmatic navigation -->
<button onclick="RouterManager.navigate('/contact')">Contact</button>

การตั้งค่า

RouterManager.init({
  mode: 'history',

  routes: [
    { path: '/', template: '/pages/home.html' },
    { path: '/products', template: '/pages/products.html' },
    { path: '/products/:id', template: '/pages/product.html' }
  ],

  // Container for page content
  container: '#app',

  // Default route
  defaultRoute: '/',

  // 404 template
  notFoundTemplate: '/pages/404.html',

  // Scroll behavior
  scrollBehavior: 'top',  // 'top', 'restore', 'none'

  // Base path
  basePath: '',

  // API integration
  api: {
    enabled: true,
    format: '/api{path}'
  }
});

Route Definition

{
  // URL path
  path: '/users/:id',

  // Template file
  template: '/pages/user.html',

  // API endpoint
  api: '/api/users/:id',

  // Route name
  name: 'user-profile',

  // Metadata
  meta: {
    requiresAuth: true,
    title: 'User Profile'
  },

  // Before enter guard
  beforeEnter: (to, from) => {
    if (!isAuthenticated()) {
      return '/login';  // Redirect
    }
    return true;  // Allow
  }
}

API อ้างอิง

RouterManager.navigate(path, options?)

Navigate to path

Parameter Type Description
path string Target path
options.replace boolean Replace history
options.params object Query parameters
RouterManager.navigate('/users/123');
RouterManager.navigate('/search', { params: { q: 'john' } });
RouterManager.navigate('/login', { replace: true });

RouterManager.go(delta)

Navigate history

RouterManager.go(-1);  // Back
RouterManager.go(1);   // Forward

RouterManager.back()

Go back

RouterManager.back();

RouterManager.forward()

Go forward

RouterManager.forward();

RouterManager.getCurrentRoute()

Get current route info

Returns: Object

const route = RouterManager.getCurrentRoute();
// { path: '/users/123', params: { id: '123' }, query: {}, meta: {} }

RouterManager.getParams()

Get route parameters

Returns: Object

// URL: /users/123
const params = RouterManager.getParams();
// { id: '123' }

RouterManager.getQuery()

Get query parameters

Returns: Object

// URL: /search?q=john&page=2
const query = RouterManager.getQuery();
// { q: 'john', page: '2' }

RouterManager.beforeEach(guard)

Global navigation guard

Parameter Type Description
guard function Guard function
RouterManager.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth && !isAuthenticated()) {
    next('/login');
  } else {
    next();
  }
});

RouterManager.afterEach(hook)

After navigation hook

RouterManager.afterEach((to, from) => {
  document.title = to.meta.title || 'My App';
  trackPageView(to.path);
});

เหตุการณ์

Event เมื่อเกิด Detail
route:changed Route เปลี่ยน {path, params, query}
route:before ก่อน navigate {to, from}
route:after หลัง navigate {to, from}
route:error Error {error, path}
EventManager.on('route:changed', (data) => {
  console.log('Navigated to:', data.path);
});

ตัวอย่างการใช้งานจริง

Basic SPA Setup

<!DOCTYPE html>
<html>
<head>
  <title>My App</title>
</head>
<body>
  <nav>
    <a href="/">Home</a>
    <a href="/about">About</a>
    <a href="/contact">Contact</a>
  </nav>

  <main id="app">
    <!-- Page content loads here -->
  </main>

  <script src="/js/now.js"></script>
  <script>
    Now.init({
      router: {
        mode: 'history',
        container: '#app',
        routes: [
          { path: '/', template: '/pages/home.html' },
          { path: '/about', template: '/pages/about.html' },
          { path: '/contact', template: '/pages/contact.html' }
        ]
      }
    });
  </script>
</body>
</html>

Protected Routes

RouterManager.init({
  routes: [
    { path: '/', template: '/pages/home.html' },
    { path: '/login', template: '/pages/login.html', meta: { guest: true } },
    {
      path: '/dashboard',
      template: '/pages/dashboard.html',
      meta: { requiresAuth: true }
    },
    {
      path: '/admin',
      template: '/pages/admin.html',
      meta: { requiresAuth: true, role: 'admin' }
    }
  ]
});

RouterManager.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth && !AuthManager.isAuthenticated()) {
    AuthManager.saveIntendedUrl(to.path);
    return next('/login');
  }

  if (to.meta.guest && AuthManager.isAuthenticated()) {
    return next('/dashboard');
  }

  if (to.meta.role && !AuthManager.hasRole(to.meta.role)) {
    return next('/403');
  }

  next();
});

Dynamic Page Title

RouterManager.afterEach((to) => {
  const titles = {
    '/': 'Home',
    '/about': 'About Us',
    '/contact': 'Contact'
  };

  document.title = `${titles[to.path] || 'Page'} | My App`;
});

Route Parameters

// Route: /users/:id
// URL: /users/123

const route = RouterManager.getCurrentRoute();
console.log(route.params.id);  // '123'

// In template
// <h1>User {{params.id}}</h1>

ข้อควรระวัง

⚠️ 1. History Mode ต้อง Server Config

# Apache (.htaccess)
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>
# Nginx
location / {
  try_files $uri $uri/ /index.html;
}

⚠️ 2. Guard ต้องเรียก next()

// ❌ ลืมเรียก next()
RouterManager.beforeEach((to, from, next) => {
  console.log('Guard');
  // Navigation stuck!
});

// ✅ Always call next()
RouterManager.beforeEach((to, from, next) => {
  console.log('Guard');
  next();
});

เอกสารที่เกี่ยวข้อง