sessionStorage data not persisting in another or new tab - javascript

I am using sessionStorage to get some data and able to use it to create a link and append it to the page.
(function() {
var rep_info = document.getElementById('rep-info'),
session = sessionStorage.getItem('ngStorage-getRepInfo'),
obj = JSON.parse(session),
vanity_name = obj.profile.data.vanityName,
your_URL = 'https://foo.com/';
console.log(obj.profile.data.vanityName);
rep_info.insertAdjacentHTML('afterbegin', 'foo.com/' + vanity_name + '');
})();
However if I copy and paste the URL of the page which contains the script above, it doesn't fire. Instead I get this error.
Uncaught TypeError: Cannot read property 'profile' of null
But when I do a refresh, the script fires.
I should mention this page/site is accessed via user authentification i.e. username & password.
I found this solution, but I couldn't figure out how to get it going.
Thanks in advance!
UPDATE 2-1-2017
I included the library I referenced and my attempt at using to solve my problem, it's right after the module.
var LocalStoreManager = (function() {
function LocalStoreManager() {
var _this = this;
this.syncKeys = [];
this.reservedKeys = ['sync_keys', 'addToSyncKeys', 'removeFromSyncKeys',
'getSessionStorage', 'setSessionStorage', 'addToSessionStorage', 'removeFromSessionStorage', 'clearAllSessionsStorage', 'raiseDBEvent'
];
this.sessionStorageTransferHandler = function(event) {
if (!event.newValue)
return;
if (event.key == 'getSessionStorage') {
if (sessionStorage.length) {
localStorage.setItem('setSessionStorage', JSON.stringify(sessionStorage));
localStorage.removeItem('setSessionStorage');
}
} else if (event.key == 'setSessionStorage') {
if (!_this.syncKeys.length)
_this.loadSyncKeys();
var data = JSON.parse(event.newValue);
for (var key in data) {
if (_this.syncKeysContains(key))
sessionStorage.setItem(key, data[key]);
}
} else if (event.key == 'addToSessionStorage') {
var data = JSON.parse(event.newValue);
_this.addToSessionStorageHelper(data["data"], data["key"]);
} else if (event.key == 'removeFromSessionStorage') {
_this.removeFromSessionStorageHelper(event.newValue);
} else if (event.key == 'clearAllSessionsStorage' && sessionStorage.length) {
_this.clearInstanceSessionStorage();
} else if (event.key == 'addToSyncKeys') {
_this.addToSyncKeysHelper(event.newValue);
} else if (event.key == 'removeFromSyncKeys') {
_this.removeFromSyncKeysHelper(event.newValue);
}
};
}
//Todo: Implement EventListeners for the various event operations and a SessionStorageEvent for specific data keys
LocalStoreManager.prototype.initialiseStorageSyncListener = function() {
if (LocalStoreManager.syncListenerInitialised == true)
return;
LocalStoreManager.syncListenerInitialised = true;
window.addEventListener("storage", this.sessionStorageTransferHandler, false);
this.syncSessionStorage();
};
LocalStoreManager.prototype.deinitialiseStorageSyncListener = function() {
window.removeEventListener("storage", this.sessionStorageTransferHandler, false);
LocalStoreManager.syncListenerInitialised = false;
};
LocalStoreManager.prototype.syncSessionStorage = function() {
localStorage.setItem('getSessionStorage', '_dummy');
localStorage.removeItem('getSessionStorage');
};
LocalStoreManager.prototype.clearAllStorage = function() {
this.clearAllSessionsStorage();
this.clearLocalStorage();
};
LocalStoreManager.prototype.clearAllSessionsStorage = function() {
this.clearInstanceSessionStorage();
localStorage.removeItem(LocalStoreManager.DBKEY_SYNC_KEYS);
localStorage.setItem('clearAllSessionsStorage', '_dummy');
localStorage.removeItem('clearAllSessionsStorage');
};
LocalStoreManager.prototype.clearInstanceSessionStorage = function() {
sessionStorage.clear();
this.syncKeys = [];
};
LocalStoreManager.prototype.clearLocalStorage = function() {
localStorage.clear();
};
LocalStoreManager.prototype.addToSessionStorage = function(data, key) {
this.addToSessionStorageHelper(data, key);
this.addToSyncKeysBackup(key);
localStorage.setItem('addToSessionStorage', JSON.stringify({ key: key, data: data }));
localStorage.removeItem('addToSessionStorage');
};
LocalStoreManager.prototype.addToSessionStorageHelper = function(data, key) {
this.addToSyncKeysHelper(key);
sessionStorage.setItem(key, data);
};
LocalStoreManager.prototype.removeFromSessionStorage = function(keyToRemove) {
this.removeFromSessionStorageHelper(keyToRemove);
this.removeFromSyncKeysBackup(keyToRemove);
localStorage.setItem('removeFromSessionStorage', keyToRemove);
localStorage.removeItem('removeFromSessionStorage');
};
LocalStoreManager.prototype.removeFromSessionStorageHelper = function(keyToRemove) {
sessionStorage.removeItem(keyToRemove);
this.removeFromSyncKeysHelper(keyToRemove);
};
LocalStoreManager.prototype.testForInvalidKeys = function(key) {
if (!key)
throw new Error("key cannot be empty");
if (this.reservedKeys.some(function(x) {
return x == key;
}))
throw new Error("The storage key \"" + key + "\" is reserved and cannot be used. Please use a different key");
};
LocalStoreManager.prototype.syncKeysContains = function(key) {
return this.syncKeys.some(function(x) {
return x == key;
});
};
LocalStoreManager.prototype.loadSyncKeys = function() {
if (this.syncKeys.length)
return;
this.syncKeys = this.getSyncKeysFromStorage();
};
LocalStoreManager.prototype.getSyncKeysFromStorage = function(defaultValue) {
if (defaultValue === void 0) { defaultValue = []; }
var data = localStorage.getItem(LocalStoreManager.DBKEY_SYNC_KEYS);
if (data == null)
return defaultValue;
else
return JSON.parse(data);
};
LocalStoreManager.prototype.addToSyncKeys = function(key) {
this.addToSyncKeysHelper(key);
this.addToSyncKeysBackup(key);
localStorage.setItem('addToSyncKeys', key);
localStorage.removeItem('addToSyncKeys');
};
LocalStoreManager.prototype.addToSyncKeysBackup = function(key) {
var storedSyncKeys = this.getSyncKeysFromStorage();
if (!storedSyncKeys.some(function(x) {
return x == key;
})) {
storedSyncKeys.push(key);
localStorage.setItem(LocalStoreManager.DBKEY_SYNC_KEYS, JSON.stringify(storedSyncKeys));
}
};
LocalStoreManager.prototype.removeFromSyncKeysBackup = function(key) {
var storedSyncKeys = this.getSyncKeysFromStorage();
var index = storedSyncKeys.indexOf(key);
if (index > -1) {
storedSyncKeys.splice(index, 1);
localStorage.setItem(LocalStoreManager.DBKEY_SYNC_KEYS, JSON.stringify(storedSyncKeys));
}
};
LocalStoreManager.prototype.addToSyncKeysHelper = function(key) {
if (!this.syncKeysContains(key))
this.syncKeys.push(key);
};
LocalStoreManager.prototype.removeFromSyncKeys = function(key) {
this.removeFromSyncKeysHelper(key);
this.removeFromSyncKeysBackup(key);
localStorage.setItem('removeFromSyncKeys', key);
localStorage.removeItem('removeFromSyncKeys');
};
LocalStoreManager.prototype.removeFromSyncKeysHelper = function(key) {
var index = this.syncKeys.indexOf(key);
if (index > -1) {
this.syncKeys.splice(index, 1);
}
};
LocalStoreManager.prototype.saveSessionData = function(data, key) {
if (key === void 0) { key = LocalStoreManager.DBKEY_USER_DATA; }
this.testForInvalidKeys(key);
this.removeFromSyncKeys(key);
localStorage.removeItem(key);
sessionStorage.setItem(key, data);
};
LocalStoreManager.prototype.saveSyncedSessionData = function(data, key) {
if (key === void 0) { key = LocalStoreManager.DBKEY_USER_DATA; }
this.testForInvalidKeys(key);
localStorage.removeItem(key);
this.addToSessionStorage(data, key);
};
LocalStoreManager.prototype.savePermanentData = function(data, key) {
if (key === void 0) { key = LocalStoreManager.DBKEY_USER_DATA; }
this.testForInvalidKeys(key);
this.removeFromSessionStorage(key);
localStorage.setItem(key, data);
};
LocalStoreManager.prototype.moveDataToSessionStorage = function(key) {
if (key === void 0) { key = LocalStoreManager.DBKEY_USER_DATA; }
this.testForInvalidKeys(key);
var data = this.getData(key);
if (data == null)
return;
this.saveSessionData(data, key);
};
LocalStoreManager.prototype.moveDataToSyncedSessionStorage = function(key) {
if (key === void 0) { key = LocalStoreManager.DBKEY_USER_DATA; }
this.testForInvalidKeys(key);
var data = this.getData(key);
if (data == null)
return;
this.saveSyncedSessionData(data, key);
};
LocalStoreManager.prototype.moveDataToPermanentStorage = function(key) {
if (key === void 0) { key = LocalStoreManager.DBKEY_USER_DATA; }
this.testForInvalidKeys(key);
var data = this.getData(key);
if (data == null)
return;
this.savePermanentData(data, key);
};
LocalStoreManager.prototype.getData = function(key) {
if (key === void 0) { key = LocalStoreManager.DBKEY_USER_DATA; }
this.testForInvalidKeys(key);
var data = sessionStorage.getItem(key);
if (data == null)
data = localStorage.getItem(key);
return data;
};
LocalStoreManager.prototype.getDataObject = function(key) {
if (key === void 0) { key = LocalStoreManager.DBKEY_USER_DATA; }
var data = this.getData(key);
if (data != null)
return JSON.parse(data);
else
return null;
};
LocalStoreManager.prototype.deleteData = function(key) {
if (key === void 0) { key = LocalStoreManager.DBKEY_USER_DATA; }
this.testForInvalidKeys(key);
this.removeFromSessionStorage(key);
localStorage.removeItem(key);
};
return LocalStoreManager;
})();
(function() {
var localStorageMangerInstance = new LocalStoreManager();
localStorageMangerInstance.initialiseStorageSyncListener();
var data = localStorageMangerInstance.getData('ngStorage-getRepInfo'),
obj = JSON.parse(data),
vanity_name = obj.profile.data.vanityName;
localStorageMangerInstance.saveSyncedSessionData(obj, obj.profile.data.vanityName);
var rep_info = document.getElementById('rep-info'),
your_avon_URL = 'https://youravon.com/';
rep_info.insertAdjacentHTML('afterbegin', 'youravon.com/' + vanity_name + '');
console.log(vanity_name);
console.log(obj.profile.data.vanityName);
})();

Related

Javascript RangeError on website proxy RangeError: Failed to construct 'Response': The status provided (0) is outside the range [200, 599]

Image Here
Hello! I am trying to add a search bar that acts like a proxy at the top of my website. Whenever I input a website like https://stackoverflow.com I receive an error on the website. RangeError: Failed to construct 'Response': The status provided (0) is outside the range [200, 599] (Note: I am using the ultraviolet service) If you'd like to test yourself the website is https://lun.netlify.app also no errors seem to appear in the console log.
importScripts('/uv/uv.bundle.js');
importScripts('/uv/uv.config.js');
class UVServiceWorker extends EventEmitter {
constructor(config = __uv$config) {
super();
if (!config.bare) config.bare = '/bare/';
this.addresses = typeof config.bare === 'string' ? [ new URL(config.bare, location) ] : config.bare.map(str => new URL(str, location));
this.headers = {
csp: [
'cross-origin-embedder-policy',
'cross-origin-opener-policy',
'cross-origin-resource-policy',
'content-security-policy',
'content-security-policy-report-only',
'expect-ct',
'feature-policy',
'origin-isolation',
'strict-transport-security',
'upgrade-insecure-requests',
'x-content-type-options',
'x-download-options',
'x-frame-options',
'x-permitted-cross-domain-policies',
'x-powered-by',
'x-xss-protection',
],
forward: [
'accept-encoding',
'connection',
'content-length',
'content-type',
'user-agent',
],
};
this.method = {
empty: [
'GET',
'HEAD'
]
};
this.statusCode = {
empty: [
204,
304,
],
};
this.config = config;
};
async fetch({ request }) {
if (!request.url.startsWith(location.origin + (this.config.prefix || '/service/'))) {
return fetch(request);
};
try {
const ultraviolet = new Ultraviolet(this.config);
if (typeof this.config.construct === 'function') {
this.config.construct(ultraviolet, 'service');
};
const db = await ultraviolet.cookie.db();
ultraviolet.meta.origin = location.origin;
ultraviolet.meta.base = ultraviolet.meta.url = new URL(ultraviolet.sourceUrl(request.url));
const requestCtx = new RequestContext(
request,
this,
ultraviolet,
!this.method.empty.includes(request.method.toUpperCase()) ? await request.blob() : null
);
if (ultraviolet.meta.url.protocol === 'blob:') {
requestCtx.blob = true;
requestCtx.base = requestCtx.url = new URL(requestCtx.url.pathname);
};
if (request.referrer && request.referrer.startsWith(location.origin)) {
const referer = new URL(ultraviolet.sourceUrl(request.referrer));
if (ultraviolet.meta.url.origin !== referer.origin && request.mode === 'cors') {
requestCtx.headers.origin = referer.origin;
};
requestCtx.headers.referer = referer.href;
};
const cookies = await ultraviolet.cookie.getCookies(db) || [];
const cookieStr = ultraviolet.cookie.serialize(cookies, ultraviolet.meta, false);
const browser = Ultraviolet.Bowser.getParser(self.navigator.userAgent).getBrowserName();
if (browser === 'Firefox' && !(request.destination === 'iframe' || request.destination === 'document')) {
requestCtx.forward.shift();
};
if (cookieStr) requestCtx.headers.cookie = cookieStr;
const reqEvent = new HookEvent(requestCtx, null, null);
this.emit('request', reqEvent);
if (reqEvent.intercepted) return reqEvent.returnValue;
const response = await fetch(requestCtx.send);
if (response.status === 500) {
return Promise.reject('');
};
const responseCtx = new ResponseContext(requestCtx, response, this);
const resEvent = new HookEvent(responseCtx, null, null);
this.emit('beforemod', resEvent);
if (resEvent.intercepted) return resEvent.returnValue;
for (const name of this.headers.csp) {
if (responseCtx.headers[name]) delete responseCtx.headers[name];
};
if (responseCtx.headers.location) {
responseCtx.headers.location = ultraviolet.rewriteUrl(responseCtx.headers.location);
};
if (responseCtx.headers['set-cookie']) {
Promise.resolve(ultraviolet.cookie.setCookies(responseCtx.headers['set-cookie'], db, ultraviolet.meta)).then(() => {
self.clients.matchAll().then(function (clients){
clients.forEach(function(client){
client.postMessage({
msg: 'updateCookies',
url: ultraviolet.meta.url.href,
});
});
});
});
delete responseCtx.headers['set-cookie'];
};
if (responseCtx.body) {
switch(request.destination) {
case 'script':
case 'worker':
responseCtx.body = `if (!self.__uv && self.importScripts) importScripts('${__uv$config.bundle}', '${__uv$config.config}', '${__uv$config.handler}');\n`;
responseCtx.body += ultraviolet.js.rewrite(
await response.text()
);
break;
case 'style':
responseCtx.body = ultraviolet.rewriteCSS(
await response.text()
);
break;
case 'iframe':
case 'document':
if (isHtml(ultraviolet.meta.url, (responseCtx.headers['content-type'] || ''))) {
responseCtx.body = ultraviolet.rewriteHtml(
await response.text(),
{
document: true ,
injectHead: ultraviolet.createHtmlInject(
this.config.handler,
this.config.bundle,
this.config.config,
ultraviolet.cookie.serialize(cookies, ultraviolet.meta, true),
request.referrer
)
}
);
};
};
};
if (requestCtx.headers.accept === 'text/event-stream') {
responseCtx.headers['content-type'] = 'text/event-stream';
};
this.emit('response', resEvent);
if (resEvent.intercepted) return resEvent.returnValue;
return new Response(responseCtx.body, {
headers: responseCtx.headers,
status: responseCtx.status,
statusText: responseCtx.statusText,
});
} catch(err) {
return new Response(err.toString(), {
status: 500,
});
};
};
getBarerResponse(response) {
const headers = {};
const raw = JSON.parse(response.headers.get('x-bare-headers'));
for (const key in raw) {
headers[key.toLowerCase()] = raw[key];
};
return {
headers,
status: +response.headers.get('x-bare-status'),
statusText: response.headers.get('x-bare-status-text'),
body: !this.statusCode.empty.includes(+response.headers.get('x-bare-status')) ? response.body : null,
};
};
get address() {
return this.addresses[Math.floor(Math.random() * this.addresses.length)];
};
static Ultraviolet = Ultraviolet;
};
self.UVServiceWorker = UVServiceWorker;
class ResponseContext {
constructor(request, response, worker) {
const { headers, status, statusText, body } = !request.blob ? worker.getBarerResponse(response) : {
status: response.status,
statusText: response.statusText,
headers: Object.fromEntries([...response.headers.entries()]),
body: response.body,
};
this.request = request;
this.raw = response;
this.ultraviolet = request.ultraviolet;
this.headers = headers;
this.status = status;
this.statusText = statusText;
this.body = body;
};
get url() {
return this.request.url;
}
get base() {
return this.request.base;
};
set base(val) {
this.request.base = val;
};
};
class RequestContext {
constructor(request, worker, ultraviolet, body = null) {
this.ultraviolet = ultraviolet;
this.request = request;
this.headers = Object.fromEntries([...request.headers.entries()]);
this.method = request.method;
this.forward = [...worker.headers.forward];
this.address = worker.address;
this.body = body || null;
this.redirect = request.redirect;
this.credentials = 'omit';
this.mode = request.mode === 'cors' ? request.mode : 'same-origin';
this.blob = false;
};
get send() {
return new Request((!this.blob ? this.address.href + 'v1/' : 'blob:' + location.origin + this.url.pathname), {
method: this.method,
headers: {
'x-bare-protocol': this.url.protocol,
'x-bare-host': this.url.hostname,
'x-bare-path': this.url.pathname + this.url.search,
'x-bare-port': this.url.port || (this.url.protocol === 'https:' ? '443' : '80'),
'x-bare-headers': JSON.stringify(this.headers),
'x-bare-forward-headers': JSON.stringify(this.forward),
},
redirect: this.redirect,
credentials: this.credentials,
mode: location.origin !== this.address.origin ? 'cors' : this.mode,
body: this.body
});
};
get url() {
return this.ultraviolet.meta.url;
};
set url(val) {
this.ultraviolet.meta.url = val;
};
get base() {
return this.ultraviolet.meta.base;
};
set base(val) {
this.ultraviolet.meta.base = val;
};
}
function isHtml(url, contentType = '') {
return (Ultraviolet.mime.contentType((contentType || url.pathname)) || 'text/html').split(';')[0] === 'text/html';
};
class HookEvent {
#intercepted;
#returnValue;
constructor(data = {}, target = null, that = null) {
this.#intercepted = false;
this.#returnValue = null;
this.data = data;
this.target = target;
this.that = that;
};
get intercepted() {
return this.#intercepted;
};
get returnValue() {
return this.#returnValue;
};
respondWith(input) {
this.#returnValue = input;
this.#intercepted = true;
};
};
var R = typeof Reflect === 'object' ? Reflect : null
var ReflectApply = R && typeof R.apply === 'function'
? R.apply
: function ReflectApply(target, receiver, args) {
return Function.prototype.apply.call(target, receiver, args);
}
var ReflectOwnKeys
if (R && typeof R.ownKeys === 'function') {
ReflectOwnKeys = R.ownKeys
} else if (Object.getOwnPropertySymbols) {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target)
.concat(Object.getOwnPropertySymbols(target));
};
} else {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target);
};
}
function ProcessEmitWarning(warning) {
if (console && console.warn) console.warn(warning);
}
var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
return value !== value;
}
function EventEmitter() {
EventEmitter.init.call(this);
}
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._eventsCount = 0;
EventEmitter.prototype._maxListeners = undefined;
var defaultMaxListeners = 10;
function checkListener(listener) {
if (typeof listener !== 'function') {
throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
}
}
Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
enumerable: true,
get: function() {
return defaultMaxListeners;
},
set: function(arg) {
if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
}
defaultMaxListeners = arg;
}
});
EventEmitter.init = function() {
if (this._events === undefined ||
this._events === Object.getPrototypeOf(this)._events) {
this._events = Object.create(null);
this._eventsCount = 0;
}
this._maxListeners = this._maxListeners || undefined;
};
EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
}
this._maxListeners = n;
return this;
};
function _getMaxListeners(that) {
if (that._maxListeners === undefined)
return EventEmitter.defaultMaxListeners;
return that._maxListeners;
}
EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
return _getMaxListeners(this);
};
EventEmitter.prototype.emit = function emit(type) {
var args = [];
for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
var doError = (type === 'error');
var events = this._events;
if (events !== undefined)
doError = (doError && events.error === undefined);
else if (!doError)
return false;
if (doError) {
var er;
if (args.length > 0)
er = args[0];
if (er instanceof Error) {
throw er;
}
var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
err.context = er;
throw err;
}
var handler = events[type];
if (handler === undefined)
return false;
if (typeof handler === 'function') {
ReflectApply(handler, this, args);
} else {
var len = handler.length;
var listeners = arrayClone(handler, len);
for (var i = 0; i < len; ++i)
ReflectApply(listeners[i], this, args);
}
return true;
};
function _addListener(target, type, listener, prepend) {
var m;
var events;
var existing;
checkListener(listener);
events = target._events;
if (events === undefined) {
events = target._events = Object.create(null);
target._eventsCount = 0;
} else {
if (events.newListener !== undefined) {
target.emit('newListener', type,
listener.listener ? listener.listener : listener);
events = target._events;
}
existing = events[type];
}
if (existing === undefined) {
existing = events[type] = listener;
++target._eventsCount;
} else {
if (typeof existing === 'function') {
existing = events[type] =
prepend ? [listener, existing] : [existing, listener];
} else if (prepend) {
existing.unshift(listener);
} else {
existing.push(listener);
}
// Check for listener leak
m = _getMaxListeners(target);
if (m > 0 && existing.length > m && !existing.warned) {
existing.warned = true;
var w = new Error('Possible EventEmitter memory leak detected. ' +
existing.length + ' ' + String(type) + ' listeners ' +
'added. Use emitter.setMaxListeners() to ' +
'increase limit');
w.name = 'MaxListenersExceededWarning';
w.emitter = target;
w.type = type;
w.count = existing.length;
ProcessEmitWarning(w);
}
}
return target;
}
EventEmitter.prototype.addListener = function addListener(type, listener) {
return _addListener(this, type, listener, false);
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.prependListener =
function prependListener(type, listener) {
return _addListener(this, type, listener, true);
};
function onceWrapper() {
if (!this.fired) {
this.target.removeListener(this.type, this.wrapFn);
this.fired = true;
if (arguments.length === 0)
return this.listener.call(this.target);
return this.listener.apply(this.target, arguments);
}
}
function _onceWrap(target, type, listener) {
var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
var wrapped = onceWrapper.bind(state);
wrapped.listener = listener;
state.wrapFn = wrapped;
return wrapped;
}
EventEmitter.prototype.once = function once(type, listener) {
checkListener(listener);
this.on(type, _onceWrap(this, type, listener));
return this;
};
EventEmitter.prototype.prependOnceListener =
function prependOnceListener(type, listener) {
checkListener(listener);
this.prependListener(type, _onceWrap(this, type, listener));
return this;
};
EventEmitter.prototype.removeListener =
function removeListener(type, listener) {
var list, events, position, i, originalListener;
checkListener(listener);
events = this._events;
if (events === undefined)
return this;
list = events[type];
if (list === undefined)
return this;
if (list === listener || list.listener === listener) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else {
delete events[type];
if (events.removeListener)
this.emit('removeListener', type, list.listener || listener);
}
} else if (typeof list !== 'function') {
position = -1;
for (i = list.length - 1; i >= 0; i--) {
if (list[i] === listener || list[i].listener === listener) {
originalListener = list[i].listener;
position = i;
break;
}
}
if (position < 0)
return this;
if (position === 0)
list.shift();
else {
spliceOne(list, position);
}
if (list.length === 1)
events[type] = list[0];
if (events.removeListener !== undefined)
this.emit('removeListener', type, originalListener || listener);
}
return this;
};
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
EventEmitter.prototype.removeAllListeners =
function removeAllListeners(type) {
var listeners, events, i;
events = this._events;
if (events === undefined)
return this;
if (events.removeListener === undefined) {
if (arguments.length === 0) {
this._events = Object.create(null);
this._eventsCount = 0;
} else if (events[type] !== undefined) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else
delete events[type];
}
return this;
}
if (arguments.length === 0) {
var keys = Object.keys(events);
var key;
for (i = 0; i < keys.length; ++i) {
key = keys[i];
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = Object.create(null);
this._eventsCount = 0;
return this;
}
listeners = events[type];
if (typeof listeners === 'function') {
this.removeListener(type, listeners);
} else if (listeners !== undefined) {
// LIFO order
for (i = listeners.length - 1; i >= 0; i--) {
this.removeListener(type, listeners[i]);
}
}
return this;
};
function _listeners(target, type, unwrap) {
var events = target._events;
if (events === undefined)
return [];
var evlistener = events[type];
if (evlistener === undefined)
return [];
if (typeof evlistener === 'function')
return unwrap ? [evlistener.listener || evlistener] : [evlistener];
return unwrap ?
unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
}
EventEmitter.prototype.listeners = function listeners(type) {
return _listeners(this, type, true);
};
EventEmitter.prototype.rawListeners = function rawListeners(type) {
return _listeners(this, type, false);
};
EventEmitter.listenerCount = function(emitter, type) {
if (typeof emitter.listenerCount === 'function') {
return emitter.listenerCount(type);
} else {
return listenerCount.call(emitter, type);
}
};
EventEmitter.prototype.listenerCount = listenerCount;
function listenerCount(type) {
var events = this._events;
if (events !== undefined) {
var evlistener = events[type];
if (typeof evlistener === 'function') {
return 1;
} else if (evlistener !== undefined) {
return evlistener.length;
}
}
return 0;
}
EventEmitter.prototype.eventNames = function eventNames() {
return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
};
function arrayClone(arr, n) {
var copy = new Array(n);
for (var i = 0; i < n; ++i)
copy[i] = arr[i];
return copy;
}
function spliceOne(list, index) {
for (; index + 1 < list.length; index++)
list[index] = list[index + 1];
list.pop();
}
function unwrapListeners(arr) {
var ret = new Array(arr.length);
for (var i = 0; i < ret.length; ++i) {
ret[i] = arr[i].listener || arr[i];
}
return ret;
}
function once(emitter, name) {
return new Promise(function (resolve, reject) {
function errorListener(err) {
emitter.removeListener(name, resolver);
reject(err);
}
function resolver() {
if (typeof emitter.removeListener === 'function') {
emitter.removeListener('error', errorListener);
}
resolve([].slice.call(arguments));
};
eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
if (name !== 'error') {
addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
}
});
}
function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
if (typeof emitter.on === 'function') {
eventTargetAgnosticAddListener(emitter, 'error', handler, flags);
}
}
function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
if (typeof emitter.on === 'function') {
if (flags.once) {
emitter.once(name, listener);
} else {
emitter.on(name, listener);
}
} else if (typeof emitter.addEventListener === 'function') {
emitter.addEventListener(name, function wrapListener(arg) {
if (flags.once) {
emitter.removeEventListener(name, wrapListener);
}
listener(arg);
});
} else {
throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
}
}

Need to work this string in as a parameter in my url

I have a filter script that ads a value to my url trough a set of checkboxes. Each checkbox group can only ad one value.
First click on a checkboxgroup looks like this:
/Network-CAT-cables?fss=yellow
Where the fss=yellow is the added parameter. A click on another chekcbox group would look like this:
/Network-CAT-cables?fss=yellow+cat6
If I check another checkbox in one of the above groups it replaces the previous value.
Now i need to add a parameter that looks like this:
&sps=d211av450240_2.0
If I set that as a value in the checkbox it kinda work. It ads the parameter and sort after it. And if i add a "normal" value it places before it. and that works too - like this:
?fss=yellow+cat5&sps=d211av450240_2.0
The problem is that when I have several of the new custom parameter in a group. In the other checkbox groups I can only have one value - and the chosen one replaces the old parameter. with the custom parameter I want to add it just ads on, instead of replaceing - like this.
?fss=yellow+cat5&sps=d211av450240_2.0+&sps=d211av450240_1.0
The correct outcome would have been
?fss=yellow+cat5&sps=d211av450240_1.0
I know this is because of the "&" in the parameter - but unsure how to work it out. I cant change the parameter either - and I know checkboxes are ment to be for multiple choices, but its like this for a reason.
My filterscript:
$(document).ready(function(){
new function(settings) {
var $separator = settings.separator || '&';
var $spaces = settings.spaces === false ? false : true;
var $suffix = settings.suffix === false ? '' : '[]';
var $prefix = settings.prefix === false ? false : true;
var $hash = $prefix ? settings.hash === true ? "#" : "?" : "";
var $numbers = settings.numbers === false ? false : true;
jQuery.query = new function() {
var is = function(o, t) {
return o != undefined && o !== null && (!!t ? o.constructor == t : true);
};
var parse = function(path) {
var m, rx = /\[([^[]*)\]/g, match = /^([^[]+)(\[.*\])?$/.exec(path), base = match[1], tokens = [];
while (m = rx.exec(match[2])) tokens.push(m[1]);
return [base, tokens];
};
var set = function(target, tokens, value) {
var o, token = tokens.shift();
if (typeof target != 'object') target = null;
if (token === "") {
if (!target) target = [];
if (is(target, Array)) {
target.push(tokens.length == 0 ? value : set(null, tokens.slice(0), value));
} else if (is(target, Object)) {
var i = 0;
while (target[i++] != null);
target[--i] = tokens.length == 0 ? value : set(target[i], tokens.slice(0), value);
} else {
target = [];
target.push(tokens.length == 0 ? value : set(null, tokens.slice(0), value));
}
} else if (token && token.match(/^\s*[0-9]+\s*$/)) {
var index = parseInt(token, 10);
if (!target) target = [];
target[index] = tokens.length == 0 ? value : set(target[index], tokens.slice(0), value);
} else if (token) {
var index = token.replace(/^\s*|\s*$/g, "");
if (!target) target = {};
if (is(target, Array)) {
var temp = {};
for (var i = 0; i < target.length; ++i) {
temp[i] = target[i];
}
target = temp;
}
target[index] = tokens.length == 0 ? value : set(target[index], tokens.slice(0), value);
} else {
return value;
}
return target;
};
var queryObject = function(a) {
var self = this;
self.keys = {};
if (a.queryObject) {
jQuery.each(a.get(), function(key, val) {
self.SET(key, val);
});
} else {
self.parseNew.apply(self, arguments);
}
return self;
};
queryObject.prototype = {
queryObject: true,
parseNew: function(){
var self = this;
self.keys = {};
jQuery.each(arguments, function() {
var q = "" + this;
q = q.replace(/^[?#]/,''); // remove any leading ? || #
q = q.replace(/[;&]$/,''); // remove any trailing & || ;
if ($spaces) q = q.replace(/[+]/g,' '); // replace +'s with spaces
jQuery.each(q.split(/[&;]/), function(){
var key = decodeURIComponent(this.split('=')[0] || "");
var val = decodeURIComponent(this.split('=')[1] || "");
if (!key) return;
if ($numbers) {
if (/^[+-]?[0-9]+\.[0-9]*$/.test(val)) // simple float regex
val = parseFloat(val);
else if (/^[+-]?[0-9]+$/.test(val)) // simple int regex
val = parseInt(val, 10);
}
val = (!val && val !== 0) ? true : val;
self.SET(key, val);
});
});
return self;
},
has: function(key, type) {
var value = this.get(key);
return is(value, type);
},
GET: function(key) {
if (!is(key)) return this.keys;
var parsed = parse(key), base = parsed[0], tokens = parsed[1];
var target = this.keys[base];
while (target != null && tokens.length != 0) {
target = target[tokens.shift()];
}
return typeof target == 'number' ? target : target || "";
},
get: function(key) {
var target = this.GET(key);
if (is(target, Object))
return jQuery.extend(true, {}, target);
else if (is(target, Array))
return target.slice(0);
return target;
},
SET: function(key, val) {
var value = !is(val) ? null : val;
var parsed = parse(key), base = parsed[0], tokens = parsed[1];
var target = this.keys[base];
this.keys[base] = set(target, tokens.slice(0), value);
return this;
},
set: function(key, val) {
return this.copy().SET(key, val);
},
REMOVE: function(key) {
return this.SET(key, null).COMPACT();
},
remove: function(key) {
return this.copy().REMOVE(key);
},
EMPTY: function() {
var self = this;
jQuery.each(self.keys, function(key, value) {
delete self.keys[key];
});
return self;
},
load: function(url) {
var hash = url.replace(/^.*?[#](.+?)(?:\?.+)?$/, "$1");
var search = url.replace(/^.*?[?](.+?)(?:#.+)?$/, "$1");
return new queryObject(url.length == search.length ? '' : search, url.length == hash.length ? '' : hash);
},
empty: function() {
return this.copy().EMPTY();
},
copy: function() {
return new queryObject(this);
},
COMPACT: function() {
function build(orig) {
var obj = typeof orig == "object" ? is(orig, Array) ? [] : {} : orig;
if (typeof orig == 'object') {
function add(o, key, value) {
if (is(o, Array))
o.push(value);
else
o[key] = value;
}
jQuery.each(orig, function(key, value) {
if (!is(value)) return true;
add(obj, key, build(value));
});
}
return obj;
}
this.keys = build(this.keys);
return this;
},
compact: function() {
return this.copy().COMPACT();
},
toString: function() {
var i = 0, queryString = [], chunks = [], self = this;
var encode = function(str) {
str = str + "";
if ($spaces) str = str.replace(/ /g, "+");
return encodeURIComponent(str);
};
var addFields = function(arr, key, value) {
if (!is(value) || value === false) return;
var o = [encode(key)];
if (value !== true) {
o.push("=");
o.push(encode(value));
}
arr.push(o.join(""));
};
var build = function(obj, base) {
var newKey = function(key) {
return !base || base == "" ? [key].join("") : [base, "[", key, "]"].join("");
};
jQuery.each(obj, function(key, value) {
if (typeof value == 'object')
build(value, newKey(key));
else
addFields(chunks, newKey(key), value);
});
};
build(this.keys);
if (chunks.length > 0) queryString.push($hash);
queryString.push(chunks.join($separator));
return queryString.join("");
}
};
return new queryObject(location.search, location.hash);
};
}(jQuery.query || {}); // Pass in jQuery.query as settings object
function removeFSS() {
ga("send", "event", "button", "click", "filter-clear", "input");
var t = encodeURI(unescape($.query.set("fss", '')));
var n = window.location.href.split("?")[0]; window.location.href = n + t
}
function getFSS() {
var D = jQuery('.filterGenius input, .filterGenius select').serializeArray();
var O = {};
jQuery.each(D, function(_, kv) {
if (O.hasOwnProperty(kv.name)) {
O[kv.name] = jQuery.makeArray(O[kv.name]);
O[kv.name].push(clean(kv.value, ""));
}
else {
O[kv.name] =kv.value;
}
});
var V = [];
for(var i in O)
if(jQuery.isArray(O[i]))
V.push(O[i].join("+"));
else
V.push(O[i]);
V = jQuery.grep(V,function(n){ return(n) });
return V.join("+");
}
$(document).ready(function () {
$(".filterGenius input").each(function () {
if (window.location.href.indexOf($(this).val()) >= 0) {
$(this).attr("checked", "checked")
}
});
$(".filterGenius select option").each(function () {
if (window.location.href.indexOf($(this).val()) >= 0) {
$(this).attr('selected', true);
}
});
$(".filterGenius input, .filterGenius select").change(function () {
var s = encodeURI(unescape(jQuery.query.set("fss", getFSS())));
var o = window.location.href.split("?")[0];
$(".filterGenius input, .filterGenius select").attr("disabled", true);
window.location.href = o + s
});
});
$('input[type="checkbox"]').on('change', function() {
$('input[name="' + this.name + '"]').not(this).prop('checked', false);
});
});

Factory pattern within Angular?

Someone mentioned I should use a true Factory pattern below so I don't have to constantly supply the typeName. How can this be accomplished within JavaScript and Angular. If it were C#, I wouldn't have a problem, but the Java reference / value types and Angular are making my brain hurt.
(function () {
'use strict';
angular
.module('blocks.object-cache');
objectCache.$inject = ['CacheFactory', '$auth'];
function objectCache(CacheFactory, $auth) {
var _options = {
maxAge : (60 * 60 * 1000),
deleteOnExpire : 'passive',
storageMode : 'localStorage'
};
var service = {
setOptions : setOptions,
getCache : getCache,
clear : clear,
getAll : getAll,
getItem : getItem,
getItems : getItems,
putItem : putItem,
putItems : putItems,
getItemsByKey : getItemsByKey,
getItemByKeyFirst : getItemByKeyFirst,
getItemByKeySingle : getItemByKeySingle,
removeItemsByKey : removeItemsByKey,
removeItemByKey : removeItemByKey,
putItemsByKey : putItemsByKey,
putItemByKey : putItemByKey
};
return service;
////////////////////////////////////////////////////////////////////////////////
function setOptions (options) {
options = options || {};
options.maxAge = options.maxAge = _options.maxAge;
options.deleteOnExpire = options.deleteOnExpire = _options.deleteOnExpire;
options.storageMode = options.storageMode = _options.storageMode;
_options = options;
}
function getCache(typeName) {
var cacheName = [getUserId(), normalizeTypeName(typeName || 'objects')].join('_');
var cache = CacheFactory(cacheName);
if (cache) { return cache; }
cache = CacheFactory(cacheName, _options);
return cache;
}
function clear (typeName) {
var cache = getCache(typeName);
cache.removeAll();
return (!cache.keys() || (cache.keys().length < 1));
}
function getAll (typeName) {
var cache = getCache(typeName);
var result = [];
(cache.keys() || []).forEach(function(key){
result.push(cache(key));
});
return result;
}
function getItem(typeName, id) {
if (typeof id == 'undefined' || !id.trim) { return null; }
var cache = getCache(typeName);
return cache.get(id);
}
function getItems(typeName, ids) {
var cache = getCache(typeName),
result = [],
_ids = [];
(ids || []).forEach(function(id){
if (_ids.indexOf(id) < 0) {
_ids.push(id);
var item = cache.get(id);
if (item) { result.push(item); }
}
});
return result;
}
function putItem(typeName, item, id, refresh) {
if (typeof item == 'undefined') { return false; }
if (typeof id == 'undefined' || !id.trim) { return false; }
var cache = getCache(typeName);
var existing = cache.get(id);
if (existing && !refresh) { return true; }
if (existing) { cache.remove(id); }
cache.put(item, id);
return (!!cache.get(id));
}
function putItems(typeName, items, idField, refresh) {
var cache = getCache(typeName);
(items || []).forEach(function(item){
var id = item[idField];
if (typeof id != 'undefined') {
var existing = cache.get(id);
if (existing && !!refresh) { cache.remove(id); }
if (!existing || !!refresh) { cache.put(item, id); }
if (!cache.get(id)) { return false; }
}
});
return true;
}
function getItemsByKey(typeName, key, value, isCaseSensitive) {
var result = [];
(getAll(typeName) || []).forEach(function(item){
var itemValue = item[key];
if (typeof itemValue != 'undefined') {
if ((typeof value == 'string') && (typeof itemValue == 'string') && (!isCaseSensitive || value.toLowerCase() == itemValue.toLowerCase())) {
result.push(item);
} else if (((typeof value) == (typeof itemValue)) && (value == itemValue)) {
result.push(item);
} else {
// Other scenarios?
}
}
});
return result;
}
function getItemByKeyFirst(typeName, key, value, isCaseSensitive) {
var items = getItemsByKey(typeName, key, value, isCaseSensitive) || [];
return (items.length > 0) ? items[0] : null;
}
function getItemByKeySingle(typeName, key, value, isCaseSensitive) {
var items = getItemsByKey(typeName, key, value, isCaseSensitive) || [];
return (items.length === 0) ? items[0] : null;
}
function removeItemsByKey (typeName, keyField, values, isCaseSensitive) {
var cache = getCache(typeName),
keysToRemove = [];
(cache.keys() || []).forEach(function(key){
var item = cache.get[key],
itemValue = item[keyField];
if (typeof itemValue != 'undefined') {
for (var v = 0; v < (values || []).length; v += 1) {
if ((typeof values[v] == 'string') && (typeof itemValue == 'string') && (!isCaseSensitive || values[v].toLowerCase() == itemValue.toLowerCase())) {
keysToRemove.push(key);
break;
} else if (((typeof values[v]) == (typeof itemValue)) && (values[v] == itemValue)) {
keysToRemove.push(key);
break;
} else {
// Other scenarios?
}
}
}
});
var success = true;
keysToRemove.forEach(function(key){
cache.remove(key);
if (cache.get(key)) { success = false; }
});
return success;
}
function removeItemByKey (typeName, keyField, value, isCaseSensitive) {
return removeItemsByKey(typeName, keyField, [value], isCaseSensitive);
}
function putItemsByKey(typeName, items, keyField, refresh, isCaseSensitive) {
if (!!refresh) {
var values = _.map((items || []), keyField);
if (!removeItemsByKey(typeName, keyField, values, isCaseSensitive)) { return false; }
}
var cache = getCache(typeName);
(items || []).forEach(function(item){
var id = item[keyField];
if (typeof value != 'undefined') { cache.put(item, id); }
if (!cache.get(id)) { return false; }
});
return true;
}
function putItemByKey(typeName, item, keyField, refresh, isCaseSensitive) {
return putItemsByKey(typeName, [item], keyField, refresh, isCaseSensitive);
}
function getUserId () {
return $auth.isAuthenticated() ? ($auth.getPayload().sub || 'unknown') : 'public';
}
function normalizeTypeName (typeName) {
return typeName.split('.').join('-');
}
}
})();
I'm not an Angular guru, but couldn't you just move the functions to achieve a factory-like pattern? I have not tested this, but with about two minutes of copy-n-paste...
Edit: Removed your nested iterate functions.
(function () {
'use strict';
angular
.module('blocks.object-cache')
.service('ObjectCache', ObjectCache);
ObjectCache.$inject = ['CacheFactory', '$auth'];
function ObjectCache(CacheFactory, $auth) {
var _options = {
maxAge : (60 * 60 * 1000),
deleteOnExpire : 'passive',
storageMode : 'localStorage'
};
var factory = {
getCache : getCache
};
return factory;
////////////////////////////
function getCache(typeName, options) {
options = options || {};
options.maxAge = options.maxAge = _options.maxAge;
options.deleteOnExpire = options.deleteOnExpire = _options.deleteOnExpire;
options.storageMode = options.storageMode = _options.storageMode;
typeName = normalizeTypeName(typeName || 'objects');
var userId = getUserId() || 'public';
var name = userId + '_' + typeName;
var service = {
type : typeName,
user : userId,
name : name,
options : options,
cache : CacheFactory(name) || CacheFactory.createCache(name, options),
clear : function () {
this.cache.removeAll();
},
getAll : function () {
var result = [];
var keys = this.cache.keys() || [];
for (var i = 0; i < keys.length; i += 1) {
result.push(this.cache(keys[i]));
}
return result;
},
getItems : function (ids) {
var result = [],
_ids = [];
for (var i = 0; i < (ids || []).length; i += 1) {
var id = ids[i];
if (_ids.indexOf(id) < 0) {
_ids.push(id);
var item = this.cache.get(id);
if (item) { result.push(item); }
}
}
return result;
},
getItem : function (id) {
var items = this.getItems([id]);
return (items.length > 0) ? items[0] : null;
},
putItem : function (item, id, refresh) {
var existing = this.cache.get(id);
if (existing && !refresh) { return true; }
if (existing) { this.cache.remove(id); }
this.cache.put(item, id);
return (!!this.cache.get(id));
},
putItems : function (items, idField, refresh) {
var success = true;
for (var i = 0; i < (items || []).length; i += 1) {
var item = items[i];
var id = item[idField];
if (typeof id != 'undefined') {
if (this.putItem(item, id, refresh)) { success = false; }
}
}
return success;
},
getItemsByKey : function (key, value, isCaseSensitive) {
var result = [];
(this.getAll() || []).forEach(function(item){
var itemValue = item[key];
if (typeof itemValue != 'undefined') {
if ((typeof value == 'string') && (typeof itemValue == 'string') && (!isCaseSensitive || value.toLowerCase() == itemValue.toLowerCase())) {
result.push(item);
} else if (((typeof value) == (typeof itemValue)) && (value == itemValue)) {
result.push(item);
} else {
// Other scenarios?
}
}
});
return result;
},
getItemByKeyFirst : function (key, value, isCaseSensitive) {
var items = this.getItemsByKey(key, value, isCaseSensitive) || [];
return (items.length > 0) ? items[0] : null;
},
getItemByKeySingle : function (key, value, isCaseSensitive) {
var items = this.getItemsByKey(key, value, isCaseSensitive) || [];
return (items.length === 0) ? items[0] : null;
},
removeItemsByKey : function (keyField, values, isCaseSensitive) {
var keysToRemove = [],
keys = this.cache.keys() || [];
for (var k = 0; k < keys.length; k += 1) {
var key = keys[k];
var item = this.cache.get(key);
var itemVal = item[keyField];
if (typeof itemVal != 'undefined') {
for (var v = 0; v < (values || []).length; v += 1) {
if ((typeof values[v] == 'string') && (typeof itemVal == 'string') && (!isCaseSensitive || values[v].toLowerCase() == itemVal.toLowerCase())) {
keysToRemove.push(key);
break;
} else if (((typeof values[v]) == (typeof itemVal)) && (values[v] == itemVal)) {
keysToRemove.push(key);
break;
} else {
// Other scenarios?
}
}
}
}
var success = true;
for (var r = 0; r < keysToRemove.length; r += 1) {
this.cache.remove(keysToRemove[r]);
if (this.cache.get(keysToRemove[r])) { success = false; }
}
return success;
},
removeItemByKey : function (keyField, value, isCaseSensitive) {
return this.removeItemsByKey(keyField, [value], isCaseSensitive);
},
putItemsByKey : function(items, keyField, refresh, isCaseSensitive) {
if (!!refresh) {
var values = _.map((items || []), keyField);
if (!this.removeItemsByKey(keyField, values, isCaseSensitive)) { return false; }
}
for (var i = 0; i < (items || []).length; i += 1) {
var id = items[i][keyField];
if (typeof id != 'undefined') {
this.cache.put(items[i], id);
if (!this.cache.get(id)) { return false; }
}
}
return true;
},
putItemByKey : function (item, keyField, refresh, isCaseSensitive) {
return this.putItemsByKey([item], keyField, refresh, isCaseSensitive);
}
};
return service;
}
function getUserId () {
return $auth.isAuthenticated() ? ($auth.getPayload().sub || 'unknown') : null;
}
function normalizeTypeName (typeName) {
return typeName.split('.').join('-');
}
}
})();

Creating cookies in javascript and use it into mvc 4 action result

I have make cookies in java script page but when used in the Controller page it shows null and i Check in the browser cookies is also created so please help me for this ......
<script>
#Html.Raw(ViewBag.CallJSFuncOnPageLoad)
function IPDetction()
{
$.getJSON("http://ip-api.com/json/?callback=?", function (data) {
var items = [];
$.each(data, function (key, val)
{
if (key == 'city') {
document.cookie = "DetectedCityName=" + val;
}
if (key == 'region') {
document.cookie = "DetectedRegionName=" + val;
}
});
});
}
</script>
#{
string DetectedCityName = "Toronto";
try
{
RateMadnessfinal.DataModel.RateMadnessdbEntities db = new RateMadnessfinal.DataModel.RateMadnessdbEntities();
DetectedCityName = HttpContext.Current.Request.Cookies["DetectedCityName"].Value;
var getCityID = db.Macities.Where(c => c.CityName.Contains(DetectedCityName)).ToList();
if ((getCityID != null) && (getCityID.Count > 0))
{
DetectedCityName = getCityID.FirstOrDefault().CityName;
}
else
{
DetectedCityName = "Toronto";
}
}
catch (Exception e)
{
DetectedCityName = "Toronto";
}
}

How implement javascript Map structure with dynamic data ?

I am trying to create tree like component,
for the first level data is coming from the server ,
if the user clicks the node i need to populate the child nodes with the data from service call.
what is the best way to save the data for this tree component ?
because user will do some operations on the tree component like remove, add & move. Finally i need to send the updated data to the server .
This is the hashmap functionality I use in javascript.
I based it off the docs of java 7 hashmap.
http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
I added the load and save variables to allow JSON storage. be careful though. if you stored any complex objects(like a hashmap in a hashmap) you will lose that.
You'd have to implement your own object instantiatiors in the load and save function.
A JSfiddle to play with if you like:
http://jsfiddle.net/mdibbets/s51tubm4/
function HashMap() {
this.map = {};
this.listsize = 0;
}
HashMap.prototype._string = function(key) {
if(typeof key.toString !== 'undefined') {
return key.toString();
}
else {
throw new Error('No valid key supplied. Only supply Objects witha toString() method as keys');
}
}
HashMap.prototype.put = function(key,value) {
key = this._string(key);
if(typeof this.map[key] === 'undefined') {
this.listsize++;
}
this.map[key] = value;
}
HashMap.prototype.get = function(key) {
key = this._string(key);
return this.map[key];
}
HashMap.prototype.containsKey = function(key) {
key = this._string(key);
return !(this.map[key] === 'undefined');
}
HashMap.prototype.putAll = function(hashmap) {
if(hashmap instanceof HashMap) {
var othermap = hashmap.map;
for(var key in othermap) {
if(othermap.hasOwnProperty(key)) {
if(typeof this.map[key] === 'undefined') {
this.listsize++;
}
this.map[key] = othermap[key];
}
}
}
else {
throw new Error('No HashMap instance supplied');
}
}
HashMap.prototype.remove = function(key) {
key = this._string(key);
var ret = null;
if(typeof this.map[key] !== 'undefined') {
ret = this.map[key];
delete this.map[key];
this.listsize--;
}
return ret;
}
HashMap.prototype.clear = function() {
this.map = {};
this.listsize = 0;
}
HashMap.prototype.containsValue = function(value) {
for(var key in this.map) {
if(this.map.hasOwnProperty(key)) {
if(this.map[key] === value) {
return true;
}
}
}
return false;
}
HashMap.prototype.clone = function() {
var ret = new HashMap();
ret.map = this.map;
ret.listsize = this.listsize;
return ret;
}
HashMap.prototype.entrySet = function() {
return this.map;
}
HashMap.prototype.keySet = function() {
var ret = [];
for(var key in this.map) {
if(this.map.hasOwnProperty(key)) {
ret.push(key);
}
}
return ret;
}
HashMap.prototype.values = function() {
var ret = [];
for(var key in this.map) {
if(this.map.hasOwnProperty(key)) {
ret.push(this.map[key]);
}
}
return ret;
}
HashMap.prototype.size = function(activeCheck) {
//Active check is expensive.
if(typeof activeCheck !== 'undefined' && activeCheck) {
var count = 0;
for(var key in this.map) {
if(this.map.hasOwnProperty(key)) {
count++;
}
}
return count;
}
return this.listsize;
}
HashMap.prototype.save = function(){
return JSON.stringify(this.map);
}
HashMap.prototype.load = function(json) {
if(typeof json !== 'string') {
throw new Error("No valid input supplied. Only supply JSON Strings");
}
this.map = JSON.parse(json);
this.listsize = this.size(true);
}
var map = new HashMap();
console.log(
map.put('hello', true),
map.get('hello'),
map.put('hello',10),
map.put('world',20),
map.values(),
map.keySet(),
map.entrySet(),
map.containsValue('twoshoes'),
map.size()
);
var map2 = new HashMap();
map2.put('goody','twoshoes');
map2.putAll(map);
console.log(
map2.get('hello'),
map2.values(),
map2.keySet(),
map2.entrySet(),
map2.containsValue('twoshoes'),
map2.size()
);
var map3 = new HashMap();
map3.load(map2.save());
console.log(
map3.get('hello'),
map3.values(),
map3.keySet(),
map3.entrySet(),
map3.containsValue('twoshoes'),
map3.size()
);

Categories