Skip to content

Instantly share code, notes, and snippets.

@millermedeiros
Forked from jed/LICENSE.txt
Created May 17, 2011 14:58
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 millermedeiros/976628 to your computer and use it in GitHub Desktop.
Save millermedeiros/976628 to your computer and use it in GitHub Desktop.
route client urls with 404s and pattern captures
/**
* @param {array} routes Array that stores routes and callbacks. Even indices are patterns, odd indices as callbacks.
* @param {number} [pollInterval] Interval between each `location.hash` check.
* @param {string} [prevHash] Previous `location.hash`. Used to check if hash changed since last check.
*/
function(routes, pollInterval, prevHash){
function pollHash(){
var currentHash = location.hash,
i = 0,
routePattern,
capturingGroups;
if (currentHash != prevHash) {
while((routePattern = routes[i++]) && !(capturingGroups = routePattern.exec(currentHash))){
i++; //increment 2x since callback is at odd indices
}
routes[i](capturingGroups);
prevHash = currentHash;
}
}
pollHash();
setInterval(pollHash, pollInterval || 99);
}
function(a,b,c){function d(){var b=location.hash,d=0,e,f;if(b!=c){while((e=a[d++])&&!(f=e.exec(b)))d++;a[d](f),c=b}}d(),setInterval(d,b||99)}
Copyright (c) 2011 Jed Schmidt, http://jed.is
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{
"name": "route",
"keywords": ["router", "URL", "hash", "location", "controller"]
}
<!-- see this page here: https://s3.amazonaws.com/paulirishfanclub/index.html -->
<script>
// Define the route function
var route = function(a,b,c){function d(){var b=location.hash,d=0,e,f;if(b!=c){while((e=a[d++])&&!(f=e.exec(b)))d++;a[d](f),c=b}}d(),setInterval(d,b||99)};
// Define the renderer
function render(body) {
document.open();
document.write(
"<body style='font-size:300%;color:fuchsia;background-color:papayawhip'>" +
header +
body +
footer +
"</body>"
);
document.close()
}
// and some html
var nav = "<a href='#pics'>PICS</a> | <a href='#vids'>VIDS</a> | <a href='#home'>HOME</a>"
var header = "<header>Welcome to my Paul Irish Fanpage!</header><div>[ " + nav + " ]</div>"
var footer = "<footer>This is the footer. Make sure you check the source!</footer>"
// Route up our app!
route([
/^$/ , function(){ location.hash = "home" },
/^#home$/ , function(){ render( "Click the links above. <a href='#paul_irish'>This link</a> doesn't work." ) },
/^#pics$/ , function(){ render( '<img src="http://farm3.static.flickr.com/2557/3919895524_0386a7de8c_z.jpg">' ) },
/^#vids$/ , function(){ render( '<iframe src="http://www.youtube.com/embed/N8SS-rUEZPg" width="560" height="349"></iframe>') },
/* 404 */ , function(){ render( "404: Not found." ) }
])
</script>
@millermedeiros
Copy link
Author

there is no need to write cryptic code since JavaScript compressors like Closure Compiler, YUI Compressor and UglifyJS do a very good job at reducing the file size. The code above is way more readable than original version and doesn't require as many comments to describe what is going on. The compressed version is only 7 bytes bigger than the original code after minification using UglifyJS, I would call it premature optimization...

It is important to note that it could be further refactored to improve readability but since it is so concise and the intention here was just to show that the same code could be easily understood without comments I thought it wasn't necessary.

Check Crossroads.js if you need extra features and a more flexible solution.

It is also important to note that polling the location.hash isn't the best approach on all browsers (since the latest browsers already support onhashchange event) and that updating location.hash doesn't generate a history record on IE 6-7... I've also coded a cross-browser solution for the location.hash (Hasher) but still didn't released it.

Cheers.

PS: comments are usually a sign of confusing code, you shouldn't need comments to describe something that could be expressed with code.

@millermedeiros
Copy link
Author

@ruyadorno
Copy link

awesome refactoring, uncle bob would be proud of you, you should also have linked a good book as a reference: http://www.amazon.ca/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882
thank you miller for forcing me to read it in the first place :D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment