Router in a tweet
var router = function(b,d,a,c){(onhashchange=function(){for(a in b)if(c=RegExp("^#?"+a+"$").exec(location.hash))return d(b[a].apply(0,c.slice(1)))})()} | |
// replace hashes with HTML5 history | |
function useNiceUrls () { | |
if (history.replaceState && location.hash[1] === '/') { | |
history.replaceState(0, 0, location.origin + location.hash.slice(1)) | |
} | |
} | |
// render page with layout | |
function render (page) { | |
useNiceUrls() | |
document.body.innerHTML = ` | |
<code> | |
<ul> | |
<li><a href="#">homepage</a></li> | |
<li><a href="#/hello">simple route</a></li> | |
<li><a href="#/hello/world">route with parameters</a></li> | |
<li><a href="#/404">page not found</a></li> | |
</ul> | |
<p>${page}</p> | |
<p>URL: ${location}</p> | |
</code> | |
` | |
} | |
router({ | |
'': () => `<b>Source code:</b><br>${router}`, | |
'/hello': () => `Hello.`, | |
'/hello/([^/]+)': (name) => `Hello ${name}.`, | |
'.*': () => `Error #404.` | |
}, render) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment