0.1.5 • Published 8 years ago
plain-router v0.1.5
Plain Router
Yet another router implementation that very basic.
How to use
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);Methods of Router class
constructor(routes)
routesis 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(uri)
Dispatch a real URI and return object that contain routeName, normalized uri
(without hash) and parsed params.
uriis a URL path.urican 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';uriFor(routeName, params={}, withHash=false)
Generate URI for specific route by routeName and substitute a params instead params placeholders.
routeNameis a route name (key fromroutesobject that was passed toRouterconstructor)paramsis object, key is a name of route pattern placeholderwithHashis 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 });Helpers
onHashChange(router, handler, dispatchImmediately=true)
You can use this function to add hashchange event handler and pass result of
executing router.dispatch() to handler.