Created
July 24, 2016 14:29
-
-
Save webarthur/97b97d33e0412af60939084f125e7924 to your computer and use it in GitHub Desktop.
pushState javascript router to vanilla js framework
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
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