Last active
September 13, 2020 21:45
-
-
Save aishikaty/57125f0cc3c9bd5a8b72d7bb01bdfd4c to your computer and use it in GitHub Desktop.
Router in a tweet
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
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)))})()} |
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
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