0
1
Fork 0
hedera-web-mindshore/js/vn/hash.js

126 lines
2.4 KiB
JavaScript
Raw Normal View History

2016-09-26 09:28:47 +00:00
var HashListener = require('./hash-listener');
2016-09-26 09:28:47 +00:00
/**
* Class to handle the URL.
**/
2016-09-26 09:28:47 +00:00
module.exports =
{
_hash: null
,_hashMap: {}
,_listener: null
2019-02-05 16:20:24 +00:00
,initialize: function() {
this._listener = new HashListener();
this._hashChangedHandler = this._hashChanged.bind(this);
window.addEventListener('hashchange', this._hashChangedHandler);
this._hashChanged();
}
2019-02-05 16:20:24 +00:00
,destroy: function() {
window.removeEventListener('hashchange', this._hashChangedHandler);
}
2019-02-05 16:20:24 +00:00
,getListener: function() {
return this._listener;
}
/**
* Gets the hash part of the URL.
*
* @param {string} key The variable name
**/
2019-02-05 16:20:24 +00:00
,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
**/
2019-02-05 16:20:24 +00:00
,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
**/
2019-02-05 16:20:24 +00:00
,set: function(map) {
2015-12-10 13:48:43 +00:00
if (map)
for (var key in map)
if (map[key] === null || map[key] === undefined)
delete map[key];
var newHash = this.make(map);
2015-12-10 13:48:43 +00:00
if (!map)
map = {};
2019-02-05 16:20:24 +00:00
if (newHash !== this._hash) {
this._hashMap = map;
this._hash = newHash;
this._blockChanged = true;
location.hash = newHash;
this._blockChanged = false;
this._listener.changed();
}
}
/**
* 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
**/
2019-02-05 16:20:24 +00:00
,make: function(map, add) {
var hash = '#!';
2015-12-10 13:48:43 +00:00
if (add && map)
for (var key in this._hashMap)
if (!map[key])
map[key] = this._hashMap[key];
2019-02-05 16:20:24 +00:00
for (var key in map) {
if (hash.length > 2)
hash += '&';
2019-02-05 16:20:24 +00:00
hash += encodeURIComponent(key) +'='+ encodeURIComponent(map[key]);
}
return hash;
}
2019-02-05 16:20:24 +00:00
,_hashChanged: function() {
var newHash = location.hash;
if (this._blockChanged || newHash === this._hash)
return;
var newMap = hashMap = {};
var kvPairs = newHash.substr(2).split('&');
2019-02-05 16:20:24 +00:00
for (var i = 0; i < kvPairs.length; i++) {
var kvPair = kvPairs[i].split('=', 2);
if (kvPair[0])
2019-02-05 16:20:24 +00:00
newMap[decodeURIComponent(kvPair[0])] = decodeURIComponent(kvPair[1]);
}
this._hashMap = newMap;
this._hash = newHash;
this._listener.changed();
}
};