Skip to content

Instantly share code, notes, and snippets.

@frentsel
Last active November 29, 2015 13:54
Show Gist options
  • Save frentsel/e175621502f764ea2fd0 to your computer and use it in GitHub Desktop.
Save frentsel/e175621502f764ea2fd0 to your computer and use it in GitHub Desktop.
router.js
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Router js</title>
</head>
<body>
<h1 id="title"><?=!empty($_GET['page']) ? strip_tags($_GET['page']) : 'Home';?></h1>
<ul>
<li><a onclick="Router.go('/'); return false;" href="/">Home</a></li>
<li><a onclick="Router.go('/Info'); return false;" href="/Info">Info</a></li>
<li><a onclick="Router.go('/About'); return false;" href="/About">About</a></li>
<li><a onclick="Router.go('/page/Page-1'); return false;" href="/page/Page-1">Page 1</a></li>
<li><a onclick="Router.go('/page/Page-2'); return false;" href="/page/Page-2">Page 2</a></li>
</ul>
<script>
var Router = {
listeners: [],
url: '/',
go: function(path) {
window.history.pushState({}, '', path);
this.router();
},
add: function(path, callback) {
var mask = path.replace(/(:[^\/]+)/g, '([^\/]+)');
this.listeners.push({mask: '^'+mask+'$', callback: callback});
return this;
},
router: function(){
var url = window.location.pathname,
res = url.substr(1).split('/');
this.listeners.map(function(el){
var regV = new RegExp(el.mask);
if(regV.test(url))
el.callback(res);
});
},
run: function(){
window.addEventListener('load', this.router());
}
};
Router.add('/', function () {
document.getElementById('title').innerHTML = 'Home';
}).add('/About', function (params) {
document.getElementById('title').innerHTML = params[0];
}).add('/Info', function (params) {
document.getElementById('title').innerHTML = params[0];
}).add('/page/:page', function (params) {
document.getElementById('title').innerHTML = params[1];
}).run();
</script>
</body>
</html>
<!--
.htaccess
AddDefaultCharset utf-8
RewriteEngine On
RewriteRule ^([^/]+)/?$ index.php?page=$1 [L]
RewriteRule ^page/([^/]+)/?$ index.php?page=$1 [L]
-->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment