Skip to content

Instantly share code, notes, and snippets.

@eyy
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eyy/0c733286c65b7cc85f4d to your computer and use it in GitHub Desktop.
Save eyy/0c733286c65b7cc85f4d to your computer and use it in GitHub Desktop.
Rout.js – DOM Router
<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>
/* 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()

Rout.js

todo

  • dynamic parameters (:id)
  • no whiteflash
  • ?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment