Router - cynchro/OldSchoolFrontFrame GitHub Wiki

Router

OLS uses a hash-based router (#/route). No server-side configuration is needed — it works with any static host.


Defining routes

Routes are defined in initApp():

initApp({
  routes: {
    home: 'home',                   // #/home → modules/home/
    clientes: 'clientes',           // #/clientes → modules/clientes/
    'clientes/:id': 'perfil',       // #/clientes/42 → modules/perfil/
    configuracion: 'configuracion', // #/configuracion → modules/configuracion/
  },
  fallback: 'home',
});

The key is the URL pattern. The value is the module folder name.


URL format

Route key Navigates to Hash in browser
home modules/home/ #/home
clientes modules/clientes/ #/clientes
clientes/:id modules/perfil/ #/clientes/42

Dynamic parameters

Patterns with :param capture URL segments into ctx.props.params:

// Route: 'clientes/:id': 'perfil'
// URL: #/clientes/42

defineModule({
  mounted(ctx) {
    const id = ctx.props.params.id; // '42'
    ctx.methods.loadPerfil(ctx, id);
  },
  methods: {
    async loadPerfil(ctx, id) {
      ctx.state.cliente = await fetchCliente(id);
    },
  },
});

Multiple parameters are supported:

routes: {
  'pedidos/:clienteId/items/:itemId': 'item-detalle',
}
// ctx.props.params → { clienteId: '5', itemId: '12' }

Navigating programmatically

initApp() returns an object with a go() method:

const app = initApp({ routes: { ... } });

// Navigate to a route
app.go('#/clientes');
app.go('#/clientes/42');
app.go('#/home');

Or use standard anchor tags:

<a href="#/clientes">Ver clientes</a>
<a href="#/clientes/42">Ver cliente 42</a>

Fallback route

If the user navigates to an unknown hash or the app loads with an empty hash, the router uses the fallback route:

initApp({
  routes: { home: 'home', about: 'about' },
  fallback: 'home', // also the default if omitted
});

Route lifecycle

When the hash changes:

  1. Router resolves the new hash to a module name + params
  2. Calls destroyed() on the current module
  3. Removes the current module's HTML
  4. Loads the new module's HTML template
  5. Attaches bindings and event handlers
  6. Calls mounted() on the new module

Low-level router API

The router is available as a standalone module if needed:

import { createRouter } from './framework/router/router.js';

const router = createRouter({
  routes: { home: 'home' },
  fallback: 'home',
  onChange(moduleName, params) {
    // custom handler
  },
});

router.start();    // Begin listening to hashchange
router.stop();     // Stop listening
router.go('#/home'); // Programmatic navigation
router.resolve();  // Resolve the current hash immediately