-
-
Save irskep/704747b7a36fddd0cae7ffdf459427da to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export type RouteHandler = (...args: string[]) => void; | |
export type Route = { | |
re: RegExp | string; | |
handler: RouteHandler; | |
}; | |
class Router { | |
routes: Route[]; | |
constructor() { | |
this.routes = []; | |
window.addEventListener("popstate", (e) => this.check()); | |
} | |
getFragment(): string { | |
return new URL(window.location.href).pathname; | |
} | |
add(re: RegExp | string, handler: RouteHandler) { | |
this.routes.push({ re, handler: handler }); | |
} | |
remove(param: RouteHandler): void { | |
for (var i = 0, r; i < this.routes.length, (r = this.routes[i]); i++) { | |
if (r.handler === param || r.re.toString() === param.toString()) { | |
this.routes.splice(i, 1); | |
} | |
} | |
} | |
check(f?: string) { | |
const fragment = f || this.getFragment(); | |
for (var i = 0; i < this.routes.length; i++) { | |
const match = fragment.match(this.routes[i].re); | |
if (match) { | |
match.shift(); | |
this.routes[i].handler.apply({}, match); | |
return this; | |
} | |
} | |
console.error("No match for", fragment); | |
} | |
navigate(path: string) { | |
window.history.pushState({ path }, path, path); | |
this.check(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment