Last active
September 28, 2020 14:32
-
-
Save ali-master/d248e620dabb1104a0219bfe8bf5ecb3 to your computer and use it in GitHub Desktop.
HTML5 PushState Routing
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
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; |
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
// 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") | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great