Last active
November 29, 2015 13:54
-
-
Save frentsel/e175621502f764ea2fd0 to your computer and use it in GitHub Desktop.
router.js
This file contains hidden or 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
<!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