Yet another router implementation that very basic.
import { Router, onHashChange } from 'plain-router';
const router = new Router({
home: '/',
authSignIn: '/auth/signIn',
authSignOut: '/auth/signOut',
userView: '/user/:userId'
});
onHashChange(router, result => {
console.log(result);
});
Somewhere in templates/views:
<a href="{{ router.uriFor('userView', { userId: 1 }, true) }}">View User #1</a>
document.getElementById('link2').href = router.uriFor('authSignOut', {}, true);
-
routes
is map of route name and route pattern:
{
[ROUTE_NAME]: [URI_PATTERN]
}
Routes examples:
const routes = {
home: '/',
authSignIn: '/auth/signIn',
authSignOut: '/auth/signOut',
userView: '/user/:userId'
};
Dispatch a real URI and return object that contain routeName
, normalized uri
(without hash) and parsed params
.
-
uri
is a URL path.uri
can contain a hash char at start for easy integration withwindow.location.hash
.
const uri0 = '/';
const uri1 = '/auth/signIn';
const uri2 = '/user/1';
const uri3 = '#/user/1';
Generate URI for specific route by routeName
and substitute a params instead params placeholders.
-
routeName
is a route name (key fromroutes
object that was passed toRouter
constructor) -
params
is object, key is a name of route pattern placeholder -
withHash
is enable hash char as prefix for result URI
const uri0 = router.uriFor('home');
const uri1 = router.uriFor('authSignIn');
// route pattern: /user/:userId
// param placeholder :userId
const uri2 = router.uriFor('userView', { userId: 1 });
You can use this function to add hashchange
event handler and pass result of
executing router.dispatch()
to handler
.