const router = new Router();
router.navigate('/Post/123', 'Awesome blog post');
or with mounting point
const router = new Router('/Post');
router.navigate('/123', 'Awesome blog post');
Also has built-in history tracking via navigations:[]
const TITLE_DEFAULT = "My Blog"; | |
function sanitizePath(path) { | |
return path.toString().replace(/\/$/, '').replace(/^\//, ''); | |
} | |
export default class Router { | |
constructor(root = '/') { | |
this.navigations = []; | |
this.root = root; | |
} | |
track(navPath) { | |
const referrer = document.referrer; | |
this.navigations.push({ navPath, referrer }); | |
// temp for debugging Router | |
console.log('navigations:', this.navigations); // eslint-disable-line | |
} | |
navigate(path = '', title = TITLE_DEFAULT) { | |
const navPath = this.root + sanitizePath(path); | |
this.track(navPath); | |
document.title = title; | |
if (history && navPath) { | |
history.pushState(null, null, navPath); | |
} | |
} | |
} |