Simplest One Page Application Router for those who want to use it on Vanilla JS
Note:
If you want to use the IE compatible version use v1.1.5
npm install vanilla-router --save
bower install vanilla-router --save
var router = new Router({
mode: 'history',
page404: function (path) {
console.log('"/' + path + '" Page not found');
}
});
router.add('', function () {
console.log('Home page');
});
router.add('hello/(:any)', function (name) {
console.log('Hello, ' + name);
});
router.add('about', function () {
console.log('About Page');
});
router.addUriListener();
router.navigateTo('hello/World');
Default: "history" .
hash
- is for hashbang routes based onwindow.location.hash
history
- is for clean url routes based on HTML5 functionality. It is also provide back-compatibility for old browser.
Default: "/" .
Root represents the relative path for the project root.
Default: function that log an error in console.
Callback function for 404 page
Default: [ ]
Warning! Use it only if you have all stack with RegExp routes.
Every public methods of Router return the instance of Router, so they can be chained.
Add a route and handler for this route
path
- string | RegExphandler
- callback if the URL will match the pathoptions
- object, you can specify before unload callback
string path can contain:
- parenthesis (
( )
) - value between them is sent to callback function - wildcards (
:any
,:num
,:word
) it doesn't pass the value to callback function - named placeholder (
{variableName}
) it pass the value to the callback function
router.add('hello/world', function(){ });
router.add('hello/:word', function(){ });
router.add('hello/(:word)', function(name){ });
router.add('hello/{name}', function(name){ });
router.add(/^hello\/(\w+)/i, function(name){ });
Remove the route from current list of routes by path
Navigate to the specific URI with optional additional state of page silent is a flag, set as true, to skip check for new URL
Check the current URL for a change
Simulate the browser "Back" button
Simulate the browser "Forward" button
Go to a specific step in history
Recall current route handler with same arguments
Add the event listener for URL change
Remove the event listener for URL change
Reset all setting and state of Router
Released under the MIT license
Copyright (c) 2016 Grigore Odajiu