browser-app-router
v1.1.1
Published
A simple URL router for the browser, uses the browser history API falls back to hash-urls.
Downloads
14
Maintainers
Readme
BrowserRouter
A simple URL router for the browser, uses the browser history API falls back to hash-urls.
Install:
$ npm install browser-app-router
What BrowserRouter Looks Like
app.js:
var BrowserRouter = require('browser-app-router');
var router = new BrowserRouter({
mode: 'hash', // 'hash'|'path' defaults to 'path'
root: '/path/to/app' // only applies if mode is set to 'path'
});
router.addRoute({
title: 'App - Home', // document.title is set to this value when this route is loaded.
path: '/',
handler: function (req) {
// handle route here
// req => {
// title: 'title of route',
// fullPath: '/path/of/route?foo=bar#bar=baz'
// path: '/path/of/route'
// params: {key => value},
// searchString: '?foo=bar',
// search: {foo: 'bar'},
// hashString: '#bar=baz',
// hash: {bar: 'baz'},
// }
// to redirect a route simply call router.go('/redirect/path')
// return false to cancel url change
}
});
router.addRoute({
title: 'App - User',
path: '/{username}', // req.params => {username => value}
// path: '/user/{username*}', // matches paths /user/*
// path: '/user/{username*2}', // matches paths /user/{foo}/{bar}
// path: '/user/{username?}', // matches paths /user|/user/{foo}
handler: function (req) {
// handle route here
}
});
router.set404({
title: 'App - 404',
handler: function (req) {
// handle 404 here
}
});
router.start();
// this inits the router and load the route at the current url.
router.reload();
// this reload the route at the current url without changing history.
router.go('/path/to/route?search=search#hash=hash');
// loads the route with the given url string.
router.go404();
// loads the 404 route with the current url.
// return a message if a user should be warned about leaving the page.
// NOTE: this will not prevent the user from leaving if the choose to leave.
// event is the beforeunload event if user manually changes the url.
router.beforeRouteChange = function (event) {
if (unsavedChanges) {
return 'You have unsaved changes, are you sure you want to leave?';
}
}