- dynamic parameters (:id)
- no whiteflash
- ?
Last active
August 29, 2015 14:25
-
-
Save eyy/0c733286c65b7cc85f4d to your computer and use it in GitHub Desktop.
Rout.js – DOM 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
<style> | |
route { | |
display: block; | |
background: yellow; | |
} | |
route[path] { | |
display: none; | |
} | |
</style> | |
<ul> | |
<li><a href="#/">Home</a></li> | |
<li><a href="#/hi">Hi</a></li> | |
<li><a href="#/login">Login</a></li> | |
</ul> | |
<route> | |
<h1>Default route</h1> | |
<route>Nested default route</route> | |
<route path="hi">Hi there?</route> | |
</route> | |
<route path="login"> | |
<button type="button">Login</button> | |
</route> |
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
/* rout.js */ | |
NodeList.prototype.__proto__ = Array.prototype // from bling.js | |
var routes = [].map.call(document.getElementsByTagName('route'), function (el) { | |
var path = [], | |
siblings = el.parentNode.childNodes.filter(function (sib) { | |
return sib.tagName && sib.tagName.toLowerCase() == 'route' && sib !== el | |
}) | |
for (var parent = el.parentNode; parent && parent !== document; parent = parent.parentNode) { | |
if (parent.tagName.toLowerCase() == 'route') | |
path.push(parent.getAttribute('path')) | |
} | |
path.push(el.getAttribute('path') || '') | |
return { | |
el: el, | |
path: path.join('/'), | |
siblings: siblings | |
} | |
}) | |
function route() { | |
var params = location.hash.substr(2) | |
var r, i = routes.length | |
while (i--) { | |
r = routes[i] | |
if (r.path == params) { | |
console.log('!', r) | |
r.el.style.display = 'block' | |
r.siblings.forEach(function (sib) { | |
sib.style.display = 'none' | |
}) | |
} | |
} | |
} | |
window.addEventListener('hashchange', route) | |
route() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment