-
-
Save Tom-Millard/aaffcd09785c91e75f5350647b0345cc to your computer and use it in GitHub Desktop.
Some js code for routing
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
import App from './components/App'; | |
import Router from './components/Router'; | |
import { h, render, Component } from 'preact'; | |
App.router = new Router(); | |
App.main = document.getElementById('main'); | |
App.router.registerRoute("/releases/[from]/[to]", {args : 3, action : () => { | |
import('./components/List').then(mod => { | |
const List = mod.default; | |
render(<List />, App.main, App.main.lastChild); | |
}); | |
}}); | |
App.router.fire(window.location.pathname); |
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 default class Router { | |
constructor() { | |
this.routes = []; | |
} | |
registerRoute(key, meta) { | |
this.routes[key] = meta; | |
} | |
fire(path){ | |
let url = this.parsePath(path); | |
if(Object.keys(this.routes).indexOf(path) >= 0){ | |
return this.routes[path].action(); | |
} | |
for(let k of Object.keys(this.routes)){ | |
let route = this.routes[k]; | |
let p = k.split("/").filter((entry) => { return /\S/.test(entry); }); | |
let success = 0; | |
if(route.args !== url.length){ | |
continue; | |
} | |
for(let x = 0; x != (url.length); ++x){ | |
if(url.path[x] == p[x]){ | |
++success; | |
continue; | |
} | |
if(p[x].match(/\[(.*?)\]/g)){ | |
++success; | |
continue; | |
} | |
} | |
if(success == url.length){ | |
return this.routes[k].action(url); | |
} | |
} | |
return false; | |
} | |
fail(){ | |
console.log("404"); | |
} | |
parsePath(path){ | |
let url = {}; | |
url.path = path.split("/").filter((entry) => { return /\S/.test(entry); }); | |
url.length = url.path.length; | |
return url; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment