Routing
The client-side routing API: ROUTE(), REDIRECT(), MIDDLEWARE(), the NAV object, and the route options and events.
On this page
These functions map URLs to functions in a single-page application, and NAV holds the current state of the navigation. For an introduction with complete examples, read Routing.
API
method
ROUTE(url, callback, [middleware], [init])
Registers a function for a URL.
ROUTE(url, callback, [middleware], [init])| Parameter | Type | Description |
|---|---|---|
url |
String |
The URL of the route. It can contain dynamic segments such as {id} and environment variables such as [name]. The value of DEF.root is added in front of it. |
callback |
Function |
The function to run. It receives the values of the dynamic segments. |
middleware? |
String or Array |
A comma-separated string or an array of middleware names, roles, code lists and an options object. The options object is accepted only in an array. |
init? |
Function |
A function that runs once, on the first visit, ahead of the middleware. It receives next, which must be called to continue. |
Returns Object The NAV object, so calls can be chained.
The route for the current URL runs when the application starts. Inside the callback, this is NAV, and the values of the dynamic segments are the arguments.
The URL is compared in lowercase, so write fixed segments in lowercase. A missing trailing slash is added to the address. A static route wins over a dynamic one with the same number of segments, and registering the same URL again replaces the route.
The arguments can also be passed in these orders:
ROUTE(url, middleware, callback, [init]), withmiddlewareas an arrayROUTE(url, callback, init, [middleware])
When the current URL is in the 404 state, a route registered for it runs immediately.
ROUTE('/products/new/', function() {
console.log('form');
});
ROUTE('/products/{id}/', function(id) {
console.log('detail', id, this.url);
});
REDIRECT('/products/new/');
REDIRECT('/products/AB-15');
// Output:
// form
// detail AB-15 /products/AB-15/
ROUTE('/reports/', function() {
console.log('reports');
}, function(next) {
console.log('prepare once');
next();
});
REDIRECT('/reports/');
REDIRECT('/');
REDIRECT('/reports/');
// Output:
// prepare once
// reports
// reports
method
REDIRECT([url])
Navigates to a URL without reloading the page.
REDIRECT([url])| Parameter | Type | Description |
|---|---|---|
url? |
String |
The target URL with an optional query string. It can contain environment variables such as [name], and the value of DEF.root is added in front of it. The default value is the current URL. |
Without a URL, the current route runs again. REDIRECT('./') does the same, REDIRECT('../') goes one segment up, and REDIRECT('../../') goes two segments up. A query string can follow the dots, for example REDIRECT('../?page=2').
A word starting with @ at the end of the URL is a custom flag.
ROUTE('/users/{id}/', function(id) {
console.log('user', id, NAV.query.tab);
});
REDIRECT('/users/15/?tab=orders');
// Output:
// user 15 orders
ROUTE('/users/', function() {
console.log('list');
});
ROUTE('/users/{id}/', function(id) {
console.log('user', id);
});
REDIRECT('/users/15/');
REDIRECT('../');
console.log(NAV.url);
// Output:
// user 15
// list
// /users/
method
MIDDLEWARE(name, callback)
Registers a named middleware, or runs a list of middleware.
MIDDLEWARE(name, callback)| Parameter | Type | Description |
|---|---|---|
name |
String or Array |
The name of the middleware, or an array of names to run. |
callback |
Function |
The middleware. With an array of names, the function to call at the end. |
Returns Object The NAV object, so calls can be chained.
A middleware runs ahead of the route callback and decides if the route continues. Inside the callback, this is NAV. The callback receives:
| Argument | Type | Description |
|---|---|---|
next | Function | next() continues. next(false) and next(new Error()) stop the route. |
options | Object | The options object of the route. |
roles | Array | The roles of the route. |
route | Object | The route object. |
The chain stops as well when the URL changes while a middleware is working.
With an array of names, MIDDLEWARE(names, callback) runs those middleware one after another and then calls callback. Each middleware receives only next, and unknown names are skipped.
var user = null;
MIDDLEWARE('auth', function(next, options, roles, route) {
console.log('auth', route.id);
next(user ? undefined : false);
});
ROUTE('/admin/', function() {
console.log('admin page');
}, 'auth');
REDIRECT('/admin/');
setTimeout(function() {
user = { name: 'Ann' };
REDIRECT('/admin/');
}, 100);
// Output:
// auth /admin/
// auth /admin/
// admin page
MIDDLEWARE('first', function(next) {
console.log('first');
next();
});
MIDDLEWARE('second', function(next) {
console.log('second');
next();
});
MIDDLEWARE(['first', 'second'], function() {
console.log('done');
});
// Output:
// first
// second
// done
config
ROUTE('/items/{name}/', callback)
A dynamic segment of a route URL.
ROUTE('/items/{name}/', callback)A segment in curly brackets matches any value of that segment. The values are passed to the callback in order and are available in NAV.params. They keep their original case. The address must have the same number of segments as the route.
ROUTE('/items/{id}/{tab}/', function(id, tab) {
console.log(id, tab, JSON.stringify(NAV.params));
});
REDIRECT('/items/AB-1/Photos/');
// Output:
// AB-1 Photos ["AB-1","Photos"]
config
ROUTE(url, callback, 'name')
Runs a registered middleware for the route.
ROUTE(url, callback, 'name')A plain name in the middleware argument of ROUTE() selects a middleware registered with MIDDLEWARE(). The middleware run in the listed order, and a name that is not registered is skipped.
MIDDLEWARE('first', function(next) {
console.log('first');
next();
});
MIDDLEWARE('second', function(next) {
console.log('second');
next();
});
ROUTE('/orders/', function() {
console.log('orders');
}, 'first,second');
REDIRECT('/orders/');
// Output:
// first
// second
// orders
config
ROUTE(url, callback, ['name', '@role'])
Adds a role that middleware receive in the roles array.
ROUTE(url, callback, ['name', '@role'])An item starting with @ is passed to every middleware of the route in the roles array, without the @. Roles have no effect of their own: the middleware decides what they mean.
MIDDLEWARE('auth', function(next, options, roles) {
console.log(roles.join());
next();
});
ROUTE('/admin/', function() {
console.log('admin page');
}, ['auth', '@admin', '@editor']);
REDIRECT('/admin/');
// Output:
// admin,editor
// admin page
config
ROUTE(url, callback, '#name')
Loads a code list ahead of the route callback.
ROUTE(url, callback, '#name')An item starting with # loads the code list with that name through CL(), in its position in the middleware chain. See Global functions.
CLINIT('countries', function(next) {
console.log('loading countries');
next([{ id: 'sk', name: 'Slovakia' }]);
});
ROUTE('/orders/', function() {
console.log('orders', DEF.cl.countries.length);
}, '#countries');
REDIRECT('/orders/');
// Output:
// loading countries
// orders 1
config
ROUTE(url, callback, ['name', { key: value }])
Passes options to the middleware of the route.
ROUTE(url, callback, ['name', { key: value }])An object in the middleware array is passed to every middleware of the route as options. It is also available in options of the route object.
MIDDLEWARE('layout', function(next, options) {
console.log(options.title);
next();
});
ROUTE('/admin/', function() {
console.log('admin page');
}, ['layout', { title: 'Administration' }]);
REDIRECT('/admin/');
// Output:
// Administration
// admin page
config
REDIRECT('/url/ @name')
Emits a flag event when navigating.
REDIRECT('/url/ @name')A word starting with @ is removed from the URL, and the event @flag name is emitted ahead of the navigation. See Events.
ON('@flag audit', function() {
console.log('audit');
});
ROUTE('/orders/', function() {
console.log(NAV.url);
});
REDIRECT('/orders/ @audit');
// Output:
// audit
// /orders/
type
NAV.routes[index]
Describes one registered route.
NAV.routes[index]Middleware receive this object as the route argument, and NAV.routes contains one for each route.
| Property | Type | Description |
|---|---|---|
id | String | The URL of the route. |
url | Array | The segments of the URL. |
fn | Function | The route callback. |
priority | Number | The position in the matching order. A higher number is tried first. |
params | Array | The indexes of the dynamic segments. |
middleware | Array | The middleware names and code lists, or null. |
init | Function | The init function. It is null after it has run. |
count | Number | How many times the route has matched. |
pending | Boolean | true while the middleware or init are working. |
options | Object | The options object. |
roles | Array | The roles. |
ROUTE('/items/{id}/', function() {}, ['auth', '@admin', { title: 'Items' }]);
MIDDLEWARE('auth', function(next) {
next();
});
var route = NAV.routes[0];
console.log(route.id, JSON.stringify(route.url), JSON.stringify(route.params));
console.log(JSON.stringify(route.middleware), JSON.stringify(route.roles), route.options.title);
// Output:
// /items/{id}/ ["items","{id}"] [1]
// ["auth"] ["admin"] Items
event
ON('location', function(url) {})
Emitted when the URL changes, ahead of the route callback.
ON('location', function(url) {})| Parameter | Type | Description |
|---|---|---|
url |
String |
The path without the query string. |
ON('location', function(url) {
console.log('location', url);
});
ROUTE('/a/', function() {
console.log('route');
});
REDIRECT('/a/?page=2');
// Output:
// location /a/
// route
event
ON('404', function() {})
Emitted when no route matches the URL.
ON('404', function() {})ON('404', function() {
console.log('not found', NAV.url);
});
REDIRECT('/missing/');
// Output:
// not found /missing/
event
ON('route', function(url) {})
Emitted when a route is registered.
ON('route', function(url) {})| Parameter | Type | Description |
|---|---|---|
url |
String |
The URL of the route. |
ON('route', function(url) {
console.log('registered', url);
});
ROUTE('/a/', function() {});
// Output:
// registered /a/