Created
June 14, 2012 03:24
-
-
Save mjc-gh/2927857 to your computer and use it in GitHub Desktop.
Location Hash Wrapper
This file contains hidden or 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 LocationHash = (function(ev){ | |
var hash, changed = []; | |
function read_hash(){ | |
var list = location.hash.substr(1).split('&'); | |
hash = {}; | |
for (var i = 0, pair; pair = list[i]; i++){ | |
var split = pair.split('='); | |
if (split.length){ | |
var value = split[1].split(','); | |
hash[split[0]] = value.length > 1 ? value : value[0]; | |
} | |
} | |
for (var i = 0, cb; cb = changed[i]; i++) | |
cb(); | |
} | |
function build_param_string(type, obj){ | |
var values = []; | |
obj = obj || hash; | |
for (var i in obj){ | |
var value = obj[i]; | |
var sep = '='; | |
if (type == 'h'){ | |
values.push(i + sep + (value.join ? value.join(',') : value)); | |
} else { | |
if (!value.join) | |
value = [value]; | |
else | |
sep = '[]='; | |
for (var j = 0, val; val = value[j]; j++) | |
values.push(i + sep + val); | |
} | |
} | |
return values.join('&'); | |
} | |
ev(window).on('hashchange', read_hash); | |
read_hash(); | |
return { | |
params:function(type){ return build_param_string(type); }, | |
changed:function(callback){ changed.push(callback); }, | |
build:function(obj, type){ return build_param_string(type || 'q', obj); }, | |
get:function(key){ return hash[key]; }, | |
set:function(values){ | |
for (var key in values){ | |
var value = values[key]; | |
if (value == undefined) | |
delete hash[key]; | |
else | |
hash[key] = value; | |
} | |
location.hash = build_param_string('h'); | |
} | |
}; | |
}(_CHANGE_ME_)); |
Can now add callbacks that are triggered whenever the location hash changes via LocationHash.changed
. It is recommended to use this instead of binding directly to the hashchange
event to ensure that the LocationHash
object has been set with the latest values.
Added an external method LocationHash.build
which will build a query string (or 'hash string') from an object.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Alter
_CHANGE_ME_
to something that wraps DOM elements and has anon()
method for event binding (such jQuery's$
or d3'sd3.select
). Whatever is supplied is called withwindow
thenon
is called with'hashchange'
.