router.js
Simple client sided Javascript routing library for static websites such as documentation or personal website. See it in action here
Features
- Static & dynamic routing
- Custom 404 error handling
- Before and after router middleware
- Prefixed route paths
- Route redirection with URL generator
Overview
A simple route
var router = new router();
router.add('default', '/', function () {
/* do something */
});
A simple route using parameter
router.add('single_category', '/category/:id', function (id) {
console.log('You requested the category #' + id);
});
Set a callback when returning "route not found"
router.setErrorCallback(function () {
throw new TypeError('I think there\'s a problem.');
});
Before route middleware
router.before('*', function () {
/* do something each time the route change */
});
After router middleware
router.run(function () {
/* do something after running the router */
});
Mapping routes using a route prefix
// This will create two routes under /#/docs prefix
router.map('docs_', '/docs', [
{
name: 'intro',
route: '/',
callback: function () {
content.innerHTML = '' +
'<h1>Introduction</h1>'
;
}
},
{
name: 'get_started',
route: '/get-started',
callback: function () {
content.innerHTML = '' +
'<h1>Get started</h1>'
;
}
}
]);
API
Fetch a route by name or path
router.fetchRoute('home'); // or router.fetchRoute('/');
// with parameters
router.fetchRoute('hello', {name: 'Sundown'});
Get the current route
router.route
This will return :
{
name: [string],
route: [string],
callback: [function],
paramsEnabled: [boolean],
params: [array]
}
Set and call the not found exception (with example)
var projects = [{title: 'routerjs', description: 'routing library'}];
//overwrite the default not found exception
router.setErrorCallback(function () {
document.write('Oh no! Page not found.');
});
router.add('projects', '/projects/:title', function (sProjectTitle) {
//search for the object in array
let oProject = projects.find(function (project) { sProjectTitle === project.title });
//if the project does not exist
if (!oProject) {
router.notFoundException();
}
});
Installation (npm)
$ npm i @sundowndev/router.js
Usage
var Router = require('@sundowndev/router.js');
var router = Router();
router.add('home', '/', function () {
document.write('hello world');
});
router.run();
Installation
- Include router.js in or at the end of the
<script src="router.js"></script>
<!-- or via jsdelivr CDN (change the version) -->
<script src="https://cdn.jsdelivr.net/gh/sundowndev/router.js@<VERSION>/dist/router.min.js"></script>
- Init the router
<script>
var router = new router();
</script>
- Create some routes
router.add('home', '/', function () {
document.write('Hello!');
});
- Run the router
router.run();
License
This repository is MIT licensed.