Skip to content

Instantly share code, notes, and snippets.

@BorisKotlyarov
Last active February 26, 2017 14:24
Show Gist options
  • Save BorisKotlyarov/e5329abf724fa25ac3337ae371e1f930 to your computer and use it in GitHub Desktop.
Save BorisKotlyarov/e5329abf724fa25ac3337ae371e1f930 to your computer and use it in GitHub Desktop.
Example history router

Example

	function consoleWrite(url, route){
		console.log(`%c ${url}:`, 'color: green;', route);
	}

	window.addEventListener('load', ()=>{
		let router = new Router(consoleWrite);

		router.addRoute('/pages:page.html',consoleWrite);
		router.addRoute('/user:userName',consoleWrite);
		router.addRoute('/item:itemId/description',consoleWrite);
		router.addRoute('/items:categoryID/sort:sort',consoleWrite);
		router.addRoute('/items:categoryID/sort:sort/page:pageId',consoleWrite);

		let paths = [
			'/pages/testpage.html',
			'/pages/testpage.html.not-exist-path',
			'/user/boris',
			'/user/boris/',
			'/user/boris/not-exist-path',
			'/item/1233/description',
			'/items/3333/sort/DESC',
			'/items/3333/sort/DESC/page/7',
			'/not-exist',
		];

		paths.forEach((route) => {
			let routeObj = router._getRouteByPath(route);
			if(routeObj) {
				routeObj.controller.class(route, routeObj);
			} else {
				console.log(`%c path '${route}' is not exist`, 'color: red; font-size: 15px;');
			}
		});

	});
class Router {
constructor() {
this._routes = {};
}
addRoute(path, controller, method=''){
this._routes[path] = {class: controller, method};
}
_paramsInfo(route, path){
let routeItems = route.split('/');
let pathItems = path.split('/');
let result = {};
routeItems.forEach((item, i)=>{
if(item && item.indexOf(':')!=-1) {
let itemArr= item.split(':');
result[itemArr[1]] = pathItems[i*2];
}
});
return result;
}
_getRouteByPath(path){
let result = {};
Object.keys(this._routes).forEach((route)=>{
let parsedRoute = route.replace(/(:([a-z0-9]+?)($|\/|\.html))/ig, '/([a-z0-9]+?)$3');
let routeRegEXp = new RegExp(`^${parsedRoute}\/?$`, 'i');
let match = path.match(routeRegEXp);
if(match) {
result.paramsInfo = this._paramsInfo(route, path);
result.route = route;
result.controller = this._routes[route];
}
});
if(this._isBadResult(path, result)) {
result = undefined;
}
return result;
}
_isBadResult(path, result){
return (
path!='/' &&
result &&
result.route=='/' ||
typeof result.route=='undefined'
);
}
get currentRoute(){
return this._getRouteByPath(window.location.pathname);
}
get routes(){
return this._routes;
}
go(path=window.location.pathname){
let route = this._getRouteByPath(path);
if(route){
history.pushState({}, '', path);
if(route.controller.method) {
route.controller.class[route.controller.method](route.paramsInfo);
} else {
route.controller.class(route.paramsInfo)
}
} else {
throw new Error('Controller Not Found in router!');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment