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:
- Router resolves the new hash to a module name + params
- Calls
destroyed()on the current module - Removes the current module's HTML
- Loads the new module's HTML template
- Attaches bindings and event handlers
- 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