1"use strict"; 2 3/* 4 * very simple hash router 5 * 6 * Example: 7 * routes = [ 8 * {path:'app-a', fce: () => {console.log('path a')} }, 9 * {path:'app-b', fce: (params) => {console.log('path b', params)} }, 10 * ... 11 * ] 12 * router = new Router(routes); 13 * 14 * Html: 15 * <a href="#app-a" ... 16 * <a href="#app-b/123/ahoj" 17 */ 18 19export default class Router { 20 21 constructor(routes) { 22 23 var that = this; 24 window.addEventListener("hashchange", () => that.onHashChange(routes) ); 25 } 26 27 28 getRouteParts() { 29 // Example: 30 // '#apphash/param1/param2' => ['apphash', 'param1', 'param2'] 31 const loc = window.location.hash; 32 33 const [hash, ...rest] = decodeURI(loc).split("/"); 34 35 const path = hash.replace("#", ""); 36 return [path, ...rest]; 37 } 38 39 findRouteByPathname(routes, pathname) { 40 return routes.find((route) => route.path === pathname); 41 } 42 43 44 onHashChange(routes) { 45 const [pathname, ...params] = this.getRouteParts(); 46 // console.log('pathname:', pathname, 'params:', params); 47 48 // Find the page corresponding to the current hash value 49 const route = this.findRouteByPathname(routes, pathname); 50 // console.log('route:', route); 51 52 if (route) { 53 route.fce(params); 54 } 55 } 56 57} 58 59export function router(routes) { return new Router(routes); };
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.