Skip to content

Instantly share code, notes, and snippets.

@aishikaty
Last active September 13, 2020 21:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aishikaty/57125f0cc3c9bd5a8b72d7bb01bdfd4c to your computer and use it in GitHub Desktop.
Save aishikaty/57125f0cc3c9bd5a8b72d7bb01bdfd4c to your computer and use it in GitHub Desktop.
Router in a tweet
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)))})()}
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