Spanish Total.js
English
Documentation For AI agents
Contents

Routing

The client-side routing API: ROUTE(), REDIRECT(), MIDDLEWARE(), the NAV object, and the route options and events.

.md GitHub
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.
ParameterTypeDescription
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]), with middleware as an array
  • ROUTE(url, callback, init, [middleware])

When the current URL is in the 404 state, a route registered for it runs immediately.

Static and dynamic routes
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/
Prepare a route once
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.
ParameterTypeDescription
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.

Navigate
ROUTE('/users/{id}/', function(id) {
	console.log('user', id, NAV.query.tab);
});

REDIRECT('/users/15/?tab=orders');

// Output:
// user 15 orders
Go one level up
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.
ParameterTypeDescription
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:

ArgumentTypeDescription
nextFunctionnext() continues. next(false) and next(new Error()) stop the route.
optionsObjectThe options object of the route.
rolesArrayThe roles of the route.
routeObjectThe 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.

Protect a route
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
Run a list of middleware
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.

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.

Read two segments
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.

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.

Two middleware
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.

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.

Read the roles
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.

An item starting with # loads the code list with that name through CL(), in its position in the middleware chain. See Global functions.

Load a code list
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.

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.

Read the options
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.

A word starting with @ is removed from the URL, and the event @flag name is emitted ahead of the navigation. See Events.

React to a flag
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.

Middleware receive this object as the route argument, and NAV.routes contains one for each route.

PropertyTypeDescription
idStringThe URL of the route.
urlArrayThe segments of the URL.
fnFunctionThe route callback.
priorityNumberThe position in the matching order. A higher number is tried first.
paramsArrayThe indexes of the dynamic segments.
middlewareArrayThe middleware names and code lists, or null.
initFunctionThe init function. It is null after it has run.
countNumberHow many times the route has matched.
pendingBooleantrue while the middleware or init are working.
optionsObjectThe options object.
rolesArrayThe roles.
Inspect a route
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
method

NAV.autosave()

Saves the history to the browser storage at each navigation.

After this call, the history is stored the same way as with NAV.save() every time it changes. NAV.load() reads it back.

Keep the history
NAV.autosave();

REDIRECT('/a/');
REDIRECT('/b/');
REDIRECT('/c/');

NAV.history.length = 0;
NAV.load();
console.log(JSON.stringify(NAV.history));

// Output:
// ["/a/","/b/"]
method

NAV.back()

Goes to the previous URL.

Returns Object The NAV object, so calls can be chained.

With an empty history, it goes to /.

Go back
REDIRECT('/a/');
REDIRECT('/b/');

NAV.back();
console.log(NAV.url, NAV.next());

// Output:
// /a/ /b/
method

NAV.clientside(selector)

Turns matching elements into client-side links.
ParameterTypeDescription
selector String A jQuery selector of the links.

Returns Object The NAV object, so calls can be chained.

A click on a matching element navigates with REDIRECT(). The URL is read from href, data-href or data-url. The values # and javascript:void(0) are ignored. Elements added later work too.

Links
<a class="link" href="/about/">About</a>
<span class="link" data-href="/contact/">Contact</span>

<script>
NAV.clientside('.link');

ROUTE('/about/', function() {
	console.log('about');
});

ROUTE('/contact/', function() {
	console.log('contact');
});
</script>

<!-- Output:
about
contact
-->
method

NAV.custom()

Keeps the navigation inside the application.

Routes and REDIRECT() work as usual, and the address bar stays as it is. This suits an application embedded in another page. Call it at the start of the application.

Navigate inside the application
NAV.custom();

ROUTE('/inbox/', function() {
	console.log('inbox', NAV.url);
});

REDIRECT('/inbox/');

// Output:
// inbox /inbox/
method

NAV.forward()

Goes to the next URL after going back.

Returns Object The NAV object, so calls can be chained.

When there is no next URL, it goes to /.

Go forward
REDIRECT('/a/');
REDIRECT('/b/');

NAV.back();
NAV.forward();
console.log(NAV.url);

// Output:
// /b/
method

NAV.load()

Restores the history from the browser storage.

It reads what NAV.save() or NAV.autosave() stored. The next navigation does not add the current URL to the restored history.

Restore the history
REDIRECT('/a/');
REDIRECT('/b/');
NAV.save();

NAV.history.length = 0;
NAV.load();
console.log(JSON.stringify(NAV.history));

// Output:
// ["/a/"]
method

NAV.location(url, [skiphistory])

Runs the route of a URL without changing the address bar.
ParameterTypeDescription
url String The URL to process.
skiphistory? Boolean true does not add the current URL to the history. Default: false

NAV is updated, the events are emitted and the route runs, like in REDIRECT(). The address in the browser is not changed.

Process URLs
ROUTE('/a/', function() {
	console.log('a');
});

NAV.location('/a/');
NAV.location('/b/');
NAV.location('/c/', true);

console.log(NAV.url, JSON.stringify(NAV.history));

// Output:
// a
// /c/ ["/a/"]
method

NAV.next()

Returns the URL that NAV.forward() opens.

Returns String The next URL, or undefined when there is none.

Read the next URL
REDIRECT('/a/');
REDIRECT('/b/');

NAV.back();
console.log(NAV.next());

// Output:
// /b/
method

NAV.path(url, [delimiter])

Adds the trailing delimiter to a URL.
ParameterTypeDescription
url String The URL.
delimiter? String The character to add. Default: '/'

Returns String The URL with the delimiter.

A query string is kept after the delimiter. A URL starting with # is returned unchanged.

Normalize URLs
console.log(NAV.path('/products'));
console.log(NAV.path('/products?page=2'));
console.log(NAV.path('#inbox'));

// Output:
// /products/
// /products/?page=2
// #inbox
method

NAV.prev()

Returns the URL that NAV.back() opens.

Returns String The previous URL, or undefined when there is none.

Read the previous URL
REDIRECT('/a/');
REDIRECT('/b/');

console.log(NAV.prev());

// Output:
// /a/
method

NAV.redirect([url])

The same function as REDIRECT().
ParameterTypeDescription
url? String The target URL. The default value is the current URL.
Navigate
ROUTE('/a/', function() {
	console.log('a');
});

NAV.redirect('/a/');

// Output:
// a
method

NAV.refresh()

Runs the route of the current URL again.

The history does not change.

Run the route again
ROUTE('/a/', function() {
	console.log('a');
});

REDIRECT('/a/');
NAV.refresh();
console.log(JSON.stringify(NAV.history));

// Output:
// a
// a
// []
method

NAV.reload()

The same as NAV.refresh().
Run the route again
ROUTE('/a/', function() {
	console.log('a');
});

REDIRECT('/a/');
NAV.reload();

// Output:
// a
// a
method

NAV.remember(name, [value])

Adds a query parameter to every following REDIRECT().
ParameterTypeDescription
name String The name of the query parameter.
value? String The value, or null to stop.

Without a value, the current value of the parameter in NAV.query is kept. The value null stops adding the parameter.

Keep a parameter
NAV.remember('lang', 'de');
REDIRECT('/list/');
console.log(NAV.href);

NAV.remember('lang', null);
REDIRECT('/list/');
console.log(NAV.href);

// Output:
// /list/?lang=de
// /list/
method

NAV.remove(url)

Removes a route.
ParameterTypeDescription
url String The URL used in ROUTE().

Returns Object The NAV object, so calls can be chained.

Remove a route
ROUTE('/a/', function() {
	console.log('a');
});

NAV.remove('/a/');
REDIRECT('/a/');
console.log(NAV.is404);

// Output:
// true
method

NAV.save()

Stores the history in the browser storage once.

The previous and next URLs are written to localStorage under the key DEF.localstorage + '.nav'.

Store the history
REDIRECT('/a/');
REDIRECT('/b/');
NAV.save();

var data = JSON.parse(localStorage.getItem(DEF.localstorage + '.nav'));
console.log(JSON.stringify(data.prev));

// Output:
// ["/a/"]
method

NAV.status(code, [data])

Emits an event named after a code.
ParameterTypeDescription
code Number or String The name of the event.
data? Object The argument of the event.

Returns Object The NAV object, so calls can be chained.

This gives an application one place to handle errors.

Report an error
ON('500', function(error) {
	console.log('failed:', error);
});

NAV.status(500, 'Database is down');

// Output:
// failed: Database is down
property

NAV.hashtags

Drives the routes with the hash part of the URL.

Returns Boolean The default value is false.

Set it to true at the start of the application. Write the routes with a leading #, and navigate with links or location.hash.

Routes on the hash
NAV.hashtags = true;

ROUTE('#inbox', function() {
	console.log('inbox', NAV.url);
});

setTimeout(function() {
	location.hash = '#inbox';
}, 100);

// Output:
// inbox #inbox
property

NAV.href

The URL passed to the last navigation.

Returns String The URL with its query string.

Read the URL
REDIRECT('/search/?q=lamp');
console.log(NAV.href);

// Output:
// /search/?q=lamp
property

NAV.history

The previous URLs.

Returns Array An array of strings.

The items are paths without the query string. The last item is the most recent one.

List the previous URLs
REDIRECT('/a/?page=2');
REDIRECT('/b/');
REDIRECT('/c/');

console.log(JSON.stringify(NAV.history));

// Output:
// ["/a/","/b/"]
property

NAV.is404

Tells if no route matches the current URL.

Returns Boolean true when no route matches.

Check the state
ROUTE('/a/', function() {});

REDIRECT('/missing/');
console.log(NAV.is404);

REDIRECT('/a/');
console.log(NAV.is404);

// Output:
// true
// false
property

NAV.isback

The number of URLs to go back to.

Returns Number The number of previous URLs.

It is a path, so the markup can bind to it.

Count the previous URLs
REDIRECT('/a/');
REDIRECT('/b/');
REDIRECT('/c/');

console.log(NAV.isback);

// Output:
// 2
property

NAV.isforward

The number of URLs to go forward to.

Returns Number The number of next URLs.

It is a path, so the markup can bind to it.

Count the next URLs
REDIRECT('/a/');
REDIRECT('/b/');

NAV.back();
console.log(NAV.isforward);

// Output:
// 1
property

NAV.middlewares

The registered middleware.

Returns Object The functions, with the middleware names as keys.

List the names
MIDDLEWARE('auth', function(next) {
	next();
});

console.log(Object.keys(NAV.middlewares).join());

// Output:
// auth
property

NAV.params

The values of the dynamic segments of the current route.

Returns Array An array of strings.

It is a path, so the markup can bind to it.

Read the values
ROUTE('/items/{id}/{tab}/', function() {
	console.log(JSON.stringify(NAV.params));
});

REDIRECT('/items/15/photos/');

// Output:
// ["15","photos"]
property

NAV.query

The parsed query string of the current URL.

Returns Object The parameters. All values are strings.

The names and values are decoded, and a + becomes a space. It is a path, so the markup can bind to it.

Read the query string
REDIRECT('/search/?q=desk+lamp&page=2');
console.log(JSON.stringify(NAV.query));

// Output:
// {"q":"desk lamp","page":"2"}
property

NAV.queryraw

The query string as text.

Returns String The query string without the leading ?.

Read the text
REDIRECT('/search/?q=lamp&page=2');
console.log(NAV.queryraw);

// Output:
// q=lamp&page=2
property

NAV.routes

The registered routes.

Returns Array An array of route objects.

The array is sorted in the matching order. Each item is a route object.

List the routes
ROUTE('/items/{id}/', function() {});
ROUTE('/items/new/', function() {});

console.log(NAV.routes.map(route => route.id).join());

// Output:
// /items/new/,/items/{id}/
property

NAV.ua

Information about the browser.

Returns Object The object of MAIN.ua.

It is the same object as MAIN.ua and is available when the application has started. See MAIN.

Compare with MAIN
ROUTE('/', function() {
	console.log(NAV.ua === MAIN.ua);
});

// Output:
// true
property

NAV.url

The current path without the query string.

Returns String The path with a trailing slash.

It is a path, so the markup can bind to it with <ui-bind path="NAV.url" config="text"></ui-bind>.

Read the path
REDIRECT('/search?q=lamp');
console.log(NAV.url);

// Output:
// /search/
event

ON('location', function(url) {})

Emitted when the URL changes, ahead of the route callback.
ParameterTypeDescription
url String The path without the query string.
Watch the navigation
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.
Handle an unknown URL
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.
ParameterTypeDescription
url String The URL of the route.
Watch the registration
ON('route', function(url) {
	console.log('registered', url);
});

ROUTE('/a/', function() {});

// Output:
// registered /a/
Made in Europe