Skip to content

Instantly share code, notes, and snippets.

@mjc-gh
Created June 14, 2012 03:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mjc-gh/2927857 to your computer and use it in GitHub Desktop.
Save mjc-gh/2927857 to your computer and use it in GitHub Desktop.
Location Hash Wrapper
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_));
@mjc-gh
Copy link
Author

mjc-gh commented Jul 5, 2012

Alter _CHANGE_ME_ to something that wraps DOM elements and has an on() method for event binding (such jQuery's $ or d3's d3.select). Whatever is supplied is called with window then on is called with 'hashchange'.

@mjc-gh
Copy link
Author

mjc-gh commented Jul 15, 2012

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.

@mjc-gh
Copy link
Author

mjc-gh commented Nov 9, 2012

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