Skip to content

Instantly share code, notes, and snippets.

@webarthur
Created July 24, 2016 14:29
Show Gist options
  • Save webarthur/97b97d33e0412af60939084f125e7924 to your computer and use it in GitHub Desktop.
Save webarthur/97b97d33e0412af60939084f125e7924 to your computer and use it in GitHub Desktop.
pushState javascript router to vanilla js framework
var routes = (function(history){
var pushState = history.pushState;
history.pushState = function(state) {
typeof(history.onpushstate) == "function" && history.onpushstate({state: state});
setTimeout(routes.check, 10);
return pushState.apply(history, arguments);
};
var routes = {
root: '/',
routes: [],
alwaysFunc:function(){},
config: function(options) {
for(option in options)
this[option] = options[option];
return this;
},
on: function(re, handler) {
this.routes.push({ re: re, handler: handler});
return this;
},
default: function(handler) {
this.routes.push({ re: '', handler: handler});
return this;
},
check: function(f) {
var root = routes.clean(routes.root);
var path = decodeURI(location.pathname);
path = routes.clean(path);
path = routes.clean(path.replace(new RegExp("^"+root), ''));
console.log('pushChange', root, path);
for(var i=0; i<routes.routes.length; i++) {
var match = path.match(routes.routes[i].re);
if(match) {
match.shift();
routes.routes[i].handler.apply({}, [match]);
break;
}
}
routes.alwaysFunc(path);
return routes;
},
clean: function(path) {
return path.replace(/\/$/, '').replace(/^\//, '');
},
always: function(func){ this.alwaysFunc = func; }
};
window.addEventListener('popstate', routes.check);
window.addEventListener('DOMContentLoaded', routes.check);
return routes;
})(window.history);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment