There are three main parts to setting up jsrouter
:
(handlerName: string, handlers: object): undefined
addHandler
is used to define route handlers.
router.addHandler('home', {
enter: function({path, lastPath, queryParams, params}) {
console.log(`entered ${path} from ${lastPath}`);
},
leave: function({path, nextPath, queryParams, params}) {
console.log(`left ${path} to go to ${nextPath}`);
}
});
(matchCallback: function): undefined
map
is used to define routes.
router.map(function(match) {
match('/').to('home');
match('/profile/:id').to('profile');
match('/page/*splat').to('page');
});
(): path: string
Returns the current path (window.location.hash
). currentPath
does not include query params and ensures a leading and trailing slash.
// current hash: #/somePath/here?a=1&b=2
router.currentPath(); // => /somePath/here/
(route: string, [state: object], [options: object]): path: string
navigate
is used to change routes. It takes the path of the route as a string as the first argument, and optionally takes state as a second argument. This state is used as the state in window.replaceState
(which is called by navigate
, along with changing the window.location.hash
). If no state is given, it uses navigateState
config function to get the state.
The third option taken by navigate
is an optional options object.
trigger
(boolean): If true,handleRouteChange
will still be called onnavigate
even if the route has not changed.
router.navigate('/myRoute');
// with state
router.navigate('/myRoute', {val1: 2, val2: 'abc'});
// with options
router.navigate('/myRoute', {val1: 2, val2: 'abc'}, {trigger: true});
(): undefined
Calls window.history.back
router.back();
(): undefined
Calls window.history.forward
router.forward();
(): undefined
Calls navigate
with the currentPath without its final element. For example, if the
currentPath is /foo/bar/
, then it could call navigate('/foo/')
.
router.pop();