Skip to content

Instantly share code, notes, and snippets.

@bradoyler
Last active April 17, 2017 20:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bradoyler/adfc0e5ff6a5147fc097a7de3279d40c to your computer and use it in GitHub Desktop.
Save bradoyler/adfc0e5ff6a5147fc097a7de3279d40c to your computer and use it in GitHub Desktop.
Simple ES6 PushState Router

Usage

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);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment