Skip to content

Instantly share code, notes, and snippets.

@funkybob
Created June 26, 2016 05:25
Show Gist options
  • Save funkybob/fced789318eb17e494690ec824891bce to your computer and use it in GitHub Desktop.
Save funkybob/fced789318eb17e494690ec824891bce to your computer and use it in GitHub Desktop.
(function () {
function Router() {
EventTarget.call(this);
this.rules = [];
window.addEventListener('hashchange', this.hashChange.bind(this));
window.addEventListener('popstate', this.hashChange.bind(this));
}
Router.prototype = Object.create(EventTarget);
Router.prototype.constructor = Router;
Router.prototype.hashChange = function () {
var l = window.location;
var query = new FormData();
l.search.slice(1).split('&').forEach(function (x) {
var y = x.split('=');
if(!y[0]) return;
args.append(y[0], decodeURI(y[1]));
});
var args = {
'location': l,
'path': l.pathname,
'hash': l.hash.slice(1),
'query': query,
'match': m.slice(1)
};
var ev = new CustomEvent('routechange', {detail: args});
this.dispatchEvent(ev);
this.rules.forEach(function (x) {
var m = x[0].exec(l.href);
if(m !== null) {
x[1](args);
}
}, this);
};
Router.prototype.addRoute = function (pattern, handler) {
if(typeof pattern === 'string') pattern = RegExp(pattern);
this.rules.push([pattern, handler]);
};
Router.prototype.pushState = function () {
window.history.pushState.apply(this, arguments);
this.hashChange();
};
Router.prototype.replaceState = function () {
window.history.replaceState.apply(this, arguments);
this.hashChange();
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment