Routing
How to map URLs to functions in a single-page application with ROUTE(), REDIRECT() and NAV.
On this page
Routing lets one HTML page behave like many. The library watches the URL, runs the function registered for it, and changes the URL without reloading the page. The server must return the same application page for every URL the application uses, so that opening a link directly works too.
Declaring routes
ROUTE(url, callback, [middleware], [init]) registers a route. Parts in curly brackets are dynamic, and their values are passed to the callback in order. REDIRECT(url) navigates to a URL.
ROUTE('/', function() {
console.log('home');
});
ROUTE('/products/', function() {
console.log('list');
});
ROUTE('/products/new/', function() {
console.log('form');
});
ROUTE('/products/{id}/', function(id) {
console.log('detail', id);
});
ROUTE('/products/{id}/{tab}/', function(id, tab) {
console.log('tab', id, tab, this.url);
});
ON('ready', function() {
setTimeout(function() {
REDIRECT('/products/');
REDIRECT('/products/new/');
REDIRECT('/products/AB-15/');
REDIRECT('/products/15/photos');
}, 300);
});home
list
form
detail AB-15
tab 15 photos /products/15/photos/The route for the current URL runs when the application starts. Inside the callback, this is NAV. A URL gets a trailing slash when it has none, and a static route such as /products/new/ wins over a dynamic one such as /products/{id}/.
The URL is compared in lowercase, so write the routes in lowercase. A route with a capital letter never matches. The values of dynamic parts keep their case:
ROUTE('/team/{name}/', function(name) {
console.log(name);
});
REDIRECT('/TEAM/AnnLee/'); // AnnLeeReading the current location
ROUTE('/search/', function() {
console.log(JSON.stringify(NAV.query));
console.log(NAV.url, '|', NAV.href, '|', NAV.queryraw);
});
REDIRECT('/search/?q=lamp&page=2');{"q":"lamp","page":"2"}
/search/ | /search/?q=lamp&page=2 | q=lamp&page=2| Property | Description |
|---|---|
NAV.url | The current path without the query string. |
NAV.href | The URL passed to the last navigation. |
NAV.query | The parsed query string. All values are strings. |
NAV.queryraw | The query string without the leading ?. |
NAV.params | An array with the values of the dynamic parts. |
NAV.is404 | true when no route matches the current URL. |
NAV.history | An array of the previous URLs. |
NAV.isback | The number of URLs to go back to. |
NAV.isforward | The number of URLs to go forward to. |
NAV is a normal path, so the markup can bind to it:
<ui-bind path="NAV.url" config="text"></ui-bind>Links
A plain link reloads the page. NAV.clientside(selector) turns matching links into client-side navigation. The URL is read from href, data-href or data-url. Any element with the class exec and a data-href attribute navigates too.
<a class="link" href="/docs/about/">About</a>
<a class="link" data-href="/contact/">Contact</a>
<span class="exec" data-href="/help/">Help</span>
<script>
NAV.clientside('.link');
</script>Moving through the history
| Method | Description |
|---|---|
NAV.back() | Goes to the previous URL. |
NAV.forward() | Goes to the next URL after going back. |
NAV.prev() | Returns the previous URL. |
NAV.next() | Returns the next URL. |
NAV.refresh(), NAV.reload() | Runs the route of the current URL again. |
REDIRECT('/a/');
REDIRECT('/a/b/');
console.log(NAV.url, NAV.prev()); // /a/b/ /a/
NAV.back();
console.log(NAV.url, NAV.next()); // /a/ /a/b/
NAV.forward();
console.log(NAV.url); // /a/b/
REDIRECT('../');
console.log(NAV.url); // /a/REDIRECT('../') goes one level up. The buttons of the browser work as well.
NAV.autosave() keeps the history in the browser storage at each navigation, NAV.save() stores it once, and NAV.load() restores it:
NAV.autosave();
REDIRECT('/a/');
REDIRECT('/b/');
NAV.history.length = 0;
NAV.load();
console.log(JSON.stringify(NAV.history)); // ["/","/a/"]Middleware
A middleware runs ahead of the route callback and decides if the route continues. MIDDLEWARE(name, callback) registers one, and the third argument of ROUTE() selects them.
MIDDLEWARE('auth', function(next, options, roles, route) {
console.log('auth', JSON.stringify(options), roles.join(), route.id);
if (window.user)
next();
else
next(false);
});
ROUTE('/admin/', function() {
console.log('admin page');
}, ['auth', '@admin', '@editor', { title: 'Admin' }]);With no user, the first navigation prints only the auth line. Once window.user is set, the next one reaches the page:
auth {"title":"Admin"} admin,editor /admin/
auth {"title":"Admin"} admin,editor /admin/
admin pageThe middleware argument of ROUTE() is an array or a comma-separated string:
| Value | Meaning |
|---|---|
name | The name of a middleware. |
@name | A role, passed to the middleware in roles. |
#name | A code list to load with CL(). |
| An object | Options, passed to the middleware in options. Only in an array. |
next() continues with the next middleware. next(false) and next(new Error()) stop the route. The route callback does not run either when the user navigates elsewhere while a middleware is still working.
MIDDLEWARE('first', function(next) { console.log('first'); next(); });
MIDDLEWARE('second', function(next) { console.log('second'); next(); });
CLINIT('countries', function(next) {
console.log('loading countries');
next([{ id: 'sk', name: 'Slovakia' }]);
});
ROUTE('/orders/', function() {
console.log('orders', DEF.cl.countries.length);
}, 'first,second,#countries');first
second
loading countries
orders 1MIDDLEWARE(names, callback) with an array of names runs those middleware outside of any route and then calls the callback:
MIDDLEWARE(['first', 'second'], function() {
console.log('both done');
});Preparing a route once
The init function runs once, on the first visit of a route, and receives a next callback. It suits work such as downloading the part of the application that the route needs.
ROUTE('/reports/', function() {
console.log('reports');
}, function(next) {
console.log('prepare once');
next();
});
REDIRECT('/reports/');
REDIRECT('/');
REDIRECT('/reports/');prepare once
reports
reportsWhen a route also has middleware, init is the fourth argument of ROUTE().
Events
| Event | Arguments | Description |
|---|---|---|
location | url | The URL changes. Emitted ahead of the route callback. |
404 | No route matches the URL. | |
route | url | A new route is registered. |
ON('location', function(url) {
console.log('location', url);
});
ON('404', function() {
console.log('not found', NAV.url, NAV.is404);
});
REDIRECT('/missing/');location /missing/
not found /missing/ trueAdding and removing routes at runtime
A route registered while its URL is showing the 404 state runs immediately, so a route can arrive later from an imported file. NAV.remove(url) removes a route.
REDIRECT('/missing/');
ROUTE('/missing/', function() {
console.log('added later');
});
console.log(NAV.is404); // false
NAV.remove('/missing/');Keeping a query parameter
NAV.remember(name, value) adds a parameter to every following REDIRECT(). Passing null as the value stops it.
NAV.remember('lang', 'de');
REDIRECT('/list/');
console.log(NAV.href); // /list/?lang=de
NAV.remember('lang', null);
REDIRECT('/list/');
console.log(NAV.href); // /list/Routing with hashes
With NAV.hashtags = true, routes are driven by the hash part of the URL. Set it at the start of the application, write the routes with a leading #, and navigate with links or location.hash.
NAV.hashtags = true;
ROUTE('#inbox', function() {
console.log('inbox', NAV.url);
});
ROUTE('#sent', function() {
console.log('sent', NAV.url);
});
location.hash = '#inbox'; // inbox #inboxRouting without changing the address bar
NAV.custom() keeps all navigation inside the application. Routes and REDIRECT() work as usual, and the address bar stays as it is. This is useful for an application embedded in another page. Call it at the start of the application.
NAV.custom();
ROUTE('/', function() {
console.log('home');
});