Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var hashes = new (function () {
- var _this = this;
- var _SEPERATOR_KEY_VALUE = ":";
- var _SEPERATOR_PAIR = "|";
- var _OLD_HASHES = {};
- /**
- * Add Hash event.
- *
- * @param hash
- * @param callback
- */
- this.addHashEvent = function(hash, callback) {
- window.hashes = window.hashes || {};
- window.hashes[hash] = callback;
- };
- /**
- * When hash is change we fire this method, or you can fire manually.
- * hash must be on the following patter: key:value;key1:value, it will transform to:
- * ['key:value', 'ke1:value'] for later to be dispatch to window.hashes.key => value
- * and window.hashes.key1 = value1;
- */
- this.fireHashOnChange = function () {
- let hashes = getMapOfHash();
- for(let hash in hashes) {
- let value = hashes[hash];
- if (!window.hashes[hash]) {
- continue;
- }
- if (_this._OLD_HASHES && _this._OLD_HASHES[hash] && _this._OLD_HASHES[hash] === value) {
- continue;
- }
- let callback = window.hashes[hash];
- _this._OLD_HASHES[hash] = value;
- callback.call(_this, value);
- }
- };
- /**
- * Add/Change hash on url but maintain the actual hash already added.
- * @param hashKey
- * @param hashValue
- */
- this.addHash = function(hashKey, hashValue) {
- let hashes = getMapOfHash();
- hashes[hashKey] = hashValue;
- let fullHashes = [];
- for(let hash in hashes) {
- fullHashes.push(hash+_SEPERATOR_KEY_VALUE+hashes[hash]);
- }
- window.location.hash = fullHashes.join(_SEPERATOR_PAIR);
- }
- /**
- * Remove Hash from hashes.
- * @param hashKey
- * @param hashValue
- */
- this.removeHash = function(hashKey) {
- let hashes = getMapOfHash();
- let fullHashes = [];
- for(let hash in hashes) {
- if (hash !== hashKey) {
- fullHashes.push(hash+_SEPERATOR_KEY_VALUE+hashes[hash]);
- }
- }
- window.location.hash = fullHashes.join(_SEPERATOR_PAIR);
- }
- /**
- * Hash on Change.
- */
- let hashOnChange = function () {
- window.addEventListener("hashchange", _this.fireHashOnChange, false);
- };
- /**
- * Get all hashes from url
- */
- let getMapOfHash = function () {
- let hashes = location.hash.toString();
- let map = {};
- if (!hashes) {
- return map;
- }
- if (hashes.indexOf(";") >= -1) {
- hashes = hashes.split(_SEPERATOR_PAIR);
- } else {
- hashes = [hashes];
- }
- for(let hash of hashes) {
- hash = hash.replace("#", "");
- let parts = hash.split(_SEPERATOR_KEY_VALUE);
- map[parts[0]] = parts[1];
- }
- return map;
- }
- hashOnChange();
- window.addEventListener("hashchange", function () {
- _this.fireHashOnChange.call(_this);
- }, false);
- })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement