Skip to content

Instantly share code, notes, and snippets.

@mjc-gh
Created June 14, 2012 03:24
Show Gist options
  • 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 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