forked from verdnatura/hedera-web
124 lines
2.1 KiB
JavaScript
124 lines
2.1 KiB
JavaScript
|
/**
|
||
|
* Class to handle the URL.
|
||
|
**/
|
||
|
Vn.Hash = new Class
|
||
|
({
|
||
|
Extends: Vn.Object
|
||
|
|
||
|
,hash: null
|
||
|
,hashMap: {}
|
||
|
|
||
|
,initialize: function ()
|
||
|
{
|
||
|
this.hashChangedHandler = this.hashChanged.bind (this);
|
||
|
window.addEventListener ('hashchange', this.hashChangedHandler);
|
||
|
this.hashChanged ();
|
||
|
}
|
||
|
|
||
|
,destroy: function ()
|
||
|
{
|
||
|
this.parent ();
|
||
|
window.removeEventListener ('hashchange', this.hashChangedHandler);
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Gets the hash part of the URL.
|
||
|
*
|
||
|
* @param {string} key The variable name
|
||
|
**/
|
||
|
,get: function (key)
|
||
|
{
|
||
|
return this.hashMap[key];
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Sets the hash part of the URL, respecting the current hash variables.
|
||
|
*
|
||
|
* @param {Object} map A key-value map
|
||
|
**/
|
||
|
,add: function (map)
|
||
|
{
|
||
|
var newMap = this.hashMap;
|
||
|
|
||
|
for (var key in map)
|
||
|
newMap[key] = map[key];
|
||
|
|
||
|
this.set (newMap);
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Sets the hash part of the URL.
|
||
|
*
|
||
|
* @param {Object} map A key-value map
|
||
|
**/
|
||
|
,set: function (map)
|
||
|
{
|
||
|
for (var key in map)
|
||
|
if (map[key] === null || map[key] === undefined)
|
||
|
delete map[key];
|
||
|
|
||
|
var newHash = this.make (map);
|
||
|
|
||
|
if (newHash !== this.hash)
|
||
|
{
|
||
|
this.hashMap = map;
|
||
|
this.putHash (newHash);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Creates a URL with the given hash data.
|
||
|
*
|
||
|
* @param {Object} map A key-value map
|
||
|
* @param {boolean} add %true to combine with the current map, %false otherwise
|
||
|
* @return {String} The URL
|
||
|
**/
|
||
|
,make: function (map, add)
|
||
|
{
|
||
|
var hash = '#!';
|
||
|
|
||
|
if (add)
|
||
|
for (var key in this.hashMap)
|
||
|
if (!map[key])
|
||
|
map[key] = this.hashMap[key];
|
||
|
|
||
|
for (var key in map)
|
||
|
{
|
||
|
if (hash.length > 2)
|
||
|
hash += '&';
|
||
|
|
||
|
hash += key +'='+ map[key];
|
||
|
}
|
||
|
|
||
|
return hash;
|
||
|
}
|
||
|
|
||
|
,putHash: function (newHash)
|
||
|
{
|
||
|
location.hash = newHash;
|
||
|
this.hash = location.hash;
|
||
|
this.signalEmit ('changed');
|
||
|
}
|
||
|
|
||
|
,hashChanged: function ()
|
||
|
{
|
||
|
var newHash = location.hash;
|
||
|
|
||
|
if (newHash === this.hash)
|
||
|
return;
|
||
|
|
||
|
this.hashMap = {};
|
||
|
var kvPairs = newHash.substr(2).split ('&');
|
||
|
|
||
|
for (var i = 0; i < kvPairs.length; i++)
|
||
|
{
|
||
|
var kvPair = kvPairs[i].split ('=', 2);
|
||
|
|
||
|
if (kvPair[0])
|
||
|
this.hashMap[kvPair[0]] = kvPair[1];
|
||
|
}
|
||
|
|
||
|
this.putHash (newHash);
|
||
|
}
|
||
|
});
|