Skip to content

Instantly share code, notes, and snippets.

@tmpvar
Forked from 140bytes/LICENSE.txt
Created May 20, 2011 02:51
Show Gist options
  • Save tmpvar/982263 to your computer and use it in GitHub Desktop.
Save tmpvar/982263 to your computer and use it in GitHub Desktop.
hatch - the smallest hash based router you've ever seen
function(fn) {
var u, n, r = /[^#]*[^\/]*\/?/;
setInterval(function() {
// poll for changes, when changed (assuming there was a callback passed)
// run the logic
n = location.hash;
if (u !== n && fn) {
// save off the current path so we know when to trigger again
u = n;
// clean off the chars preceding the hash
// up to the following /
// ie: /#!/mentions becomes /mentions
// also, send that back to the caller
fn('/' + u.replace(r, ''));
}
}, 10);
}
function (a){var b,c,d=/[^#]*[^\/]*\/?/;setInterval(function(){c=location.hash,b!==c&&a&&(b=c,a("/"+b.replace(d,"")))},10)}
Copyright (c) 2011 Elijah Insua, http://tmpvar.com
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": "hatch",
"description": "The smallest hash based router ever.",
"keywords": ["router", "hash", "rules", "micro" ]
}
@heapwolf
Copy link

wow, you really managed to narrow down the features here ;)

@heapwolf
Copy link

@atk
Copy link

atk commented Jun 7, 2011

You could lose the .replace by using the RegExp directly as a function (works similar as .exec()):

location.hash == '#!/mentions' // true
/!(/?[^\/]*/?)/(location.hash) // ['!/mentions', '/mentions']

Small warning: the RegExp Object in older IE versions needs to be restarted by settings r.lastIndex to 0, if saved in a variable. Either reinstantiate the RegExp every time or be prepared for Errors in IE.

Regards, atk

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