Spanish Total.js
English
Documentation For AI agents
Contents

Routing

Map URL addresses to functions with ROUTE(), navigate with REDIRECT() and read the current state from NAV.

.md GitHub
On this page

Routing runs a function for each address of a single-page application. ROUTE() declares the addresses, REDIRECT() moves between them without reloading the page, and the global object NAV holds the current state.

The server has to return the application page for every address that a route handles, so that the browser can open those addresses directly.

Declaring routes

ROUTE(url, handler) connects an address with a function. Dynamic segments are written in curly brackets, and their values arrive as arguments of the handler:

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

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

ROUTE('/products/new/', function() {
    console.log('new product');
});

ROUTE('/products/{id}/', function(id) {
    console.log('product', id);
});

ROUTE('/products/{id}/reviews/{review}/', function(id, review) {
    console.log('review', id, review);
});
REDIRECT('/products/new/');            // new product
REDIRECT('/products/42');              // product 42
REDIRECT('/PRODUCTS/AbC/');            // product AbC
REDIRECT('/products/42/reviews/7/');   // review 42 7

Inside a handler, this is the NAV object.

How an address is matched

  • Fixed routes win over routes with dynamic segments, so /products/new/ is not handled by /products/{id}/.
  • The address must have the same number of segments as the route.
  • A missing trailing slash is added to the address.
  • The address is compared in lowercase, so write the fixed segments of a route in lowercase. The values of dynamic segments keep their original case.
  • Declaring a route with the same address replaces the earlier route.

REDIRECT(url) changes the address in the browser and runs the matching route. NAV.clientside(selector) does the same for links, so that you can write ordinary <a> elements:

<script>
    NAV.clientside('a.jR');
</script>

<a class="jR" href="/docs/">Documentation</a>

The address comes from the href, data-href or data-url attribute. The browser's back and forward buttons run the matching routes too.

REDIRECT('../') moves one segment up. REDIRECT() without an argument and NAV.refresh() run the current route again.

The current state

PropertyDescription
NAV.urlThe current address without the query string, for example /products/42/.
NAV.hrefThe address passed to the last navigation, with its query string.
NAV.paramsAn array with the values of the dynamic segments.
NAV.queryAn object with the query string.
NAV.queryrawThe query string as text.
NAV.is404true if no route matches the address.
NAV.historyAn array of the previous addresses.
NAV.isbackThe number of addresses you can go back to.
NAV.isforwardThe number of addresses you can go forward to.
NAV.routesAn array of the declared routes.
ROUTE('/search/', function() {
    console.log(NAV.url, NAV.query.q, NAV.query.page);
});

REDIRECT('/search/?q=total%20js&page=2');
// /search/ total js 2

The properties url, href, params, query, isback and isforward are also paths, so you can bind them:

<ui-bind path="NAV.url" config="text"></ui-bind>

Middleware

A middleware runs ahead of the handler and decides whether the handler runs. MIDDLEWARE(name, fn) declares one. Name it in the third argument of ROUTE():

var user = null;

MIDDLEWARE('auth', function(next, options, roles, route) {
    if (user)
        next();
    else
        next(false);
});

ROUTE('/admin/', function() {
    console.log('admin page');
}, ['auth', '@admin', { title: 'Administration' }]);

The array of a route can contain:

ItemDescription
'name'The name of a middleware.
'@name'A role. Middleware receives all roles in the roles array.
An objectOptions passed to the middleware as options.

The middleware receives next, options, roles and the route object. Calling next() continues with the next middleware. next(false) or next(new Error('...')) stops the chain, and the handler does not run.

You can also pass the array as the second argument: ROUTE('/admin/', ['auth'], handler).

Preparing a route

A function as the third argument runs once, the first time the route is opened. Call next to continue to the handler. It suits loading what a part of the application needs:

ROUTE('/reports/', function() {
    console.log('handler');
}, function(next) {
    console.log('init');
    IMPORT('once /parts/reports.html', '#content', next);
});

The first visit prints init and handler. Each next visit prints only handler. To combine it with middleware, pass the middleware as the fourth argument: ROUTE(url, handler, init, ['auth']).

Reacting to navigation

EventArgumentsWhen it is emitted
locationurlOn every navigation.
404No route matches the address.
routeurlA route has been declared.
ON('location', function(url) {
    console.log('location', url);
});

ON('404', function() {
    console.log('not found', NAV.url);
});

NAV.status(code, [data]) emits an event named after the code, which gives you one place to handle errors:

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

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

Going back and forward

NAV.back() opens the previous address and NAV.forward() the next one:

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

NAV.back();    // NAV.url is '/a/'
NAV.forward(); // NAV.url is '/b/'

NAV.prev() and NAV.next() return the address on each side without moving.

Keeping query parameters

NAV.remember(name, value) adds a query parameter to every next REDIRECT(). Use null as the value to stop:

NAV.remember('lang', 'sk');
REDIRECT('/items/');        // NAV.href is '/items/?lang=sk'

NAV.remember('lang', null);
REDIRECT('/items/');        // NAV.href is '/items/'

Removing a route

NAV.remove(url) deletes a route declared with that address.

Routing without the address bar

NAV.custom() keeps the routing inside the application: REDIRECT() runs routes and the address in the browser stays the same. Call it ahead of the first navigation. It suits embedded applications and widgets.

The current address is stored for one month and opened again on the next visit. Pass an expiration such as '1 day' to change the time, or false to store nothing:

NAV.custom();
NAV.custom('1 day');
NAV.custom(false);
Made in Europe