Skip to content

Instantly share code, notes, and snippets.

@ali-master
Last active September 28, 2020 14:32
Show Gist options
  • Save ali-master/d248e620dabb1104a0219bfe8bf5ecb3 to your computer and use it in GitHub Desktop.
Save ali-master/d248e620dabb1104a0219bfe8bf5ecb3 to your computer and use it in GitHub Desktop.
HTML5 PushState Routing
const Router = (function () {
"use strict";
/**
* @routes
* get or set routes
*/
var routes = [];
/**
* @addRoute
* add new Route logic
*/
function addRoute(route, handler) {
routes.push({parts: route.split('/'), handler: handler});
}
/**
* @load
* load router content from hash url
*/
function load(route, callback) {
window.location.hash = route;
return callback && callback(route)
}
/**
* @init
* routing the content with hash location params
*/
function init() {
const path = window.location.hash.substr(1),
parts = path.split('/'),
partsLength = parts.length;
for (let i = 0; i < routes.length; i++) {
const route = routes[i];
if (route.parts.length === partsLength) {
var params = [];
for (var j = 0; j < partsLength; j++) {
if (route.parts[j].substr(0, 1) === ':') {
params.push(parts[j]);
} else if (route.parts[j] !== parts[j]) {
break;
}
}
if (j === partsLength) {
route.handler.apply(undefined, params);
return;
}
}
}
}
window.onhashchange = init;
return {
addRoute,
load,
init
};
}());
export default Router;
// Usage
Router.addRoute('', function() {
console.log("/")
}.bind(this));
Router.addRoute('/about', function() {
console.log("/about")
}.bind(this));
Router.addRoute('/contact', function() {
console.log("/contact")
}.bind(this));
Router.init();
// load url
Router.load("/about", function(route) {
console.log("/about route")
})
@ehsanahgh
Copy link

Great

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment