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('-');
}
}
})();
Related
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);
}
}
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);
})();
i want to set my own customize form in wdCalendar add event like first name last name instead of "what". where in jquery.calendar.js i find quickadd function which one is used when user click on calendar to add event then form appear help of quickadd function but i dont know how to set custom field in this function so please help me
below one is quickadd function of jquery.calender.js
function quickadd(start, end, isallday, pos) {
if ((!option.quickAddHandler && option.quickAddUrl == "") || option.readonly) {
return;
}
var buddle = $("#bbit-cal-buddle");
if (buddle.length == 0) {
var temparr = [];
temparr.push('<div id="bbit-cal-buddle" style="z-index: 180; width: 400px;visibility:hidden;" class="bubble">');
temparr.push('<table class="bubble-table" cellSpacing="0" cellPadding="0"><tbody><tr><td class="bubble-cell-side"><div id="tl1" class="bubble-corner"><div class="bubble-sprite bubble-tl"></div></div>');
temparr.push('<td class="bubble-cell-main"><div class="bubble-top"></div><td class="bubble-cell-side"><div id="tr1" class="bubble-corner"><div class="bubble-sprite bubble-tr"></div></div> <tr><td class="bubble-mid" colSpan="3"><div style="overflow: hidden" id="bubbleContent1"><div><div></div><div class="cb-root">');
temparr.push('<table class="cb-table" cellSpacing="0" cellPadding="0"><tbody><tr><th class="cb-key">');
temparr.push(i18n.xgcalendar.time, ':</th><td class=cb-value><div id="bbit-cal-buddle-timeshow"></div></td></tr><tr><th class="cb-key">');
temparr.push(i18n.xgcalendar.content, ':</th><td class="cb-value"><div class="textbox-fill-wrapper"><div class="textbox-fill-mid"><input id="bbit-cal-what" class="textbox-fill-input"/></div></div><div class="cb-example">');
temparr.push(i18n.xgcalendar.example, '</div></td></tr></tbody></table><input id="bbit-cal-start" type="hidden"/><input id="bbit-cal-end" type="hidden"/><input id="bbit-cal-allday" type="hidden"/><input id="bbit-cal-quickAddBTN" value="');
temparr.push(i18n.xgcalendar.create_event, '" type="button"/> <SPAN id="bbit-cal-editLink" class="lk">');
temparr.push(i18n.xgcalendar.update_detail, ' <StrONG>>></StrONG></SPAN></div></div></div><tr><td><div id="bl1" class="bubble-corner"><div class="bubble-sprite bubble-bl"></div></div><td><div class="bubble-bottom"></div><td><div id="br1" class="bubble-corner"><div class="bubble-sprite bubble-br"></div></div></tr></tbody></table><div id="bubbleClose1" class="bubble-closebutton"></div><div id="prong2" class="prong"><div class=bubble-sprite></div></div></div>');
var tempquickAddHanler = temparr.join("");
temparr = null;
$(document.body).append(tempquickAddHanler);
buddle = $("#bbit-cal-buddle");
var calbutton = $("#bbit-cal-quickAddBTN");
var lbtn = $("#bbit-cal-editLink");
var closebtn = $("#bubbleClose1").click(function() {
$("#bbit-cal-buddle").css("visibility", "hidden");
realsedragevent();
});
calbutton.click(function(e) {
if (option.isloading) {
return false;
}
option.isloading = true;
var what = $("#bbit-cal-what").val();
var datestart = $("#bbit-cal-start").val();
var dateend = $("#bbit-cal-end").val();
var allday = $("#bbit-cal-allday").val();
var f = /^[^\$\<\>]+$/.test(what);
if (!f) {
alert(i18n.xgcalendar.invalid_title);
$("#bbit-cal-what").focus();
option.isloading = false;
return false;
}
var zone = new Date().getTimezoneOffset() / 60 * -1;
var param = [{ "name": "CalendarTitle", value: what },
{ "name": "CalendarStartTime", value: datestart },
{ "name": "CalendarEndTime", value: dateend },
{ "name": "IsAllDayEvent", value: allday },
{ "name": "timezone", value: zone}];
if (option.extParam) {
for (var pi = 0; pi < option.extParam.length; pi++) {
param[param.length] = option.extParam[pi];
}
}
if (option.quickAddHandler && $.isFunction(option.quickAddHandler)) {
option.quickAddHandler.call(this, param);
$("#bbit-cal-buddle").css("visibility", "hidden");
realsedragevent();
}
else {
$("#bbit-cal-buddle").css("visibility", "hidden");
var newdata = [];
var tId = -1;
option.onBeforeRequestData && option.onBeforeRequestData(2);
$.post(option.quickAddUrl, param, function(data) {
if (data) {
if (data.IsSuccess == true) {
option.isloading = false;
option.eventItems[tId][0] = data.Data;
option.eventItems[tId][8] = 1;
render();
option.onAfterRequestData && option.onAfterRequestData(2);
}
else {
option.onRequestDataError && option.onRequestDataError(2, data);
option.isloading = false;
option.onAfterRequestData && option.onAfterRequestData(2);
}
}
}, "json");
newdata.push(-1, what);
var sd = strtodate(datestart);
var ed = strtodate(dateend);
var diff = DateDiff("d", sd, ed);
newdata.push(sd, ed, allday == "1" ? 1 : 0, diff > 0 ? 1 : 0, 0);
newdata.push(-1, 0, "", "");
tId = Ind(newdata);
realsedragevent();
render();
}
});
lbtn.click(function(e) {
if (!option.EditCmdhandler) {
alert("EditCmdhandler" + i18n.xgcalendar.i_undefined);
}
else {
if (option.EditCmdhandler && $.isFunction(option.EditCmdhandler)) {
option.EditCmdhandler.call(this, ['0', $("#bbit-cal-what").val(), $("#bbit-cal-start").val(), $("#bbit-cal-end").val(), $("#bbit-cal-allday").val()]);
}
$("#bbit-cal-buddle").css("visibility", "hidden");
realsedragevent();
}
return false;
});
buddle.mousedown(function(e) { return false });
}
var dateshow = CalDateShow(start, end, !isallday, true);
var off = getbuddlepos(pos.left, pos.top);
if (off.hide) {
$("#prong2").hide()
}
else {
$("#prong2").show()
}
$("#bbit-cal-buddle-timeshow").html(dateshow);
var calwhat = $("#bbit-cal-what").val("");
$("#bbit-cal-allday").val(isallday ? "1" : "0");
$("#bbit-cal-start").val(dateFormat.call(start, i18n.xgcalendar.dateformat.fulldayvalue + " HH:mm"));
$("#bbit-cal-end").val(dateFormat.call(end, i18n.xgcalendar.dateformat.fulldayvalue + " HH:mm"));
buddle.css({ "visibility": "visible", left: off.left, top: off.top });
calwhat.blur().focus(); //add 2010-01-26 blur() fixed chrome
$(document).one("mousedown", function() {
$("#bbit-cal-buddle").css("visibility", "hidden");
realsedragevent();
});
return false;
}
could i add ajax link on add event and display custom form and add data to database ?
is there any solution of this type to direct open popup as in add event as like open in edit event ?
And Here we go..
just copy paste this code in your jquery.form.js
it will provide you and extra field to input text.
jquery.form.js
<script>
(function($) {
$.fn.ajaxSubmit = function(options) {
if (!this.length) {
log('ajaxSubmit: skipping submit process - no element selected');
return this;
}
if (typeof options == 'function')
options = { success: options };
options = $.extend({
url: this.attr('action') || window.location.toString(),
type: this.attr('method') || 'GET'
}, options || {});
var veto = {};
this.trigger('form-pre-serialize', [this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
return this;
}
if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSerialize callback');
return this;
}
var a = this.formToArray(options.semantic);
if (options.data) {
options.extraData = options.data;
for (var n in options.data) {
if(options.data[n] instanceof Array) {
for (var k in options.data[n])
a.push( { name: n, value: options.data[n][k] } )
}
else
a.push( { name: n, value: options.data[n] } );
}
}
if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSubmit callback');
return this;
}
this.trigger('form-submit-validate', [a, this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
return this;
}
var q = $.param(a);
if (options.type.toUpperCase() == 'GET') {
options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
options.data = null;
}
else
options.data = q;
var $form = this, callbacks = [];
if (options.resetForm) callbacks.push(function() { $form.resetForm(); });
if (options.clearForm) callbacks.push(function() { $form.clearForm(); });
if (!options.dataType && options.target) {
var oldSuccess = options.success || function(){};
callbacks.push(function(data) {
$(options.target).html(data).each(oldSuccess, arguments);
});
}
else if (options.success)
callbacks.push(options.success);
options.success = function(data, status) {
for (var i=0, max=callbacks.length; i < max; i++)
callbacks[i].apply(options, [data, status, $form]);
};
var files = $('input:file', this).fieldValue();
var found = false;
for (var j=0; j < files.length; j++)
if (files[j])
found = true;
if (options.iframe || found) {
if ($.browser.safari && options.closeKeepAlive)
$.get(options.closeKeepAlive, fileUpload);
else
fileUpload();
}
else
$.ajax(options);
this.trigger('form-submit-notify', [this, options]);
return this;
function fileUpload() {
var form = $form[0];
if ($(':input[#name=submit]', form).length) {
alert('Error: Form elements must not be named "submit".');
return;
}
var opts = $.extend({}, $.ajaxSettings, options);
var s = jQuery.extend(true, {}, $.extend(true, {}, $.ajaxSettings), opts);
var id = 'jqFormIO' + (new Date().getTime());
var $io = $('<iframe id="' + id + '" name="' + id + '" />');
var io = $io[0];
if ($.browser.msie || $.browser.opera)
io.src = 'javascript:false;document.write("");';
$io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
var xhr = {
aborted: 0,
responseText: null,
responseXML: null,
status: 0,
statusText: 'n/a',
getAllResponseHeaders: function() {},
getResponseHeader: function() {},
setRequestHeader: function() {},
abort: function() {
this.aborted = 1;
$io.attr('src','about:blank');
}
};
var g = opts.global;
if (g && ! $.active++) $.event.trigger("ajaxStart");
if (g) $.event.trigger("ajaxSend", [xhr, opts]);
if (s.beforeSend && s.beforeSend(xhr, s) === false) {
s.global && jQuery.active--;
return;
}
if (xhr.aborted)
return;
var cbInvoked = 0;
var timedOut = 0;
var sub = form.clk;
if (sub) {
var n = sub.name;
if (n && !sub.disabled) {
options.extraData = options.extraData || {};
options.extraData[n] = sub.value;
if (sub.type == "image") {
options.extraData[name+'.x'] = form.clk_x;
options.extraData[name+'.y'] = form.clk_y;
}
}
}
setTimeout(function() {
var t = $form.attr('target'), a = $form.attr('action');
$form.attr({
target: id,
method: 'POST',
action: opts.url
});
if (! options.skipEncodingOverride) {
$form.attr({
encoding: 'multipart/form-data',
enctype: 'multipart/form-data'
});
}
if (opts.timeout)
setTimeout(function() { timedOut = true; cb(); }, opts.timeout);
var extraInputs = [];
try {
if (options.extraData)
for (var n in options.extraData)
extraInputs.push(
$('<input type="hidden" name="'+n+'" value="'+options.extraData[n]+'" />')
.appendTo(form)[0]);
$io.appendTo('body');
io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
form.submit();
}
finally {
$form.attr('action', a);
t ? $form.attr('target', t) : $form.removeAttr('target');
$(extraInputs).remove();
}
}, 10);
function cb() {
if (cbInvoked++) return;
io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);
var operaHack = 0;
var ok = true;
try {
if (timedOut) throw 'timeout';
var data, doc;
doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;
if (doc.body == null && !operaHack && $.browser.opera) {
operaHack = 1;
cbInvoked--;
setTimeout(cb, 100);
return;
}
xhr.responseText = doc.body ? doc.body.innerHTML : null;
xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
xhr.getResponseHeader = function(header){
var headers = {'content-type': opts.dataType};
return headers[header];
};
if (opts.dataType == 'json' || opts.dataType == 'script') {
var ta = doc.getElementsByTagName('textarea')[0];
xhr.responseText = ta ? ta.value : xhr.responseText;
}
else if (opts.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
xhr.responseXML = toXml(xhr.responseText);
}
data = $.httpData(xhr, opts.dataType);
}
catch(e){
ok = false;
$.handleError(opts, xhr, 'error', e);
}
if (ok) {
opts.success(data, 'success');
if (g) $.event.trigger("ajaxSuccess", [xhr, opts]);
}
if (g) $.event.trigger("ajaxComplete", [xhr, opts]);
if (g && ! --$.active) $.event.trigger("ajaxStop");
if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error');
// clean up
setTimeout(function() {
$io.remove();
xhr.responseXML = null;
}, 100);
};
function toXml(s, doc) {
if (window.ActiveXObject) {
doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = 'false';
doc.loadXML(s);
}
else
doc = (new DOMParser()).parseFromString(s, 'text/xml');
return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null;
};
};
};
$.fn.ajaxForm = function(options) {
return this.ajaxFormUnbind().bind('submit.form-plugin',function() {
$(this).ajaxSubmit(options);
return false;
}).each(function() {
$(":submit,input:image", this).bind('click.form-plugin',function(e) {
var form = this.form;
form.clk = this;
if (this.type == 'image') {
if (e.offsetX != undefined) {
form.clk_x = e.offsetX;
form.clk_y = e.offsetY;
} else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
var offset = $(this).offset();
form.clk_x = e.pageX - offset.left;
form.clk_y = e.pageY - offset.top;
} else {
form.clk_x = e.pageX - this.offsetLeft;
form.clk_y = e.pageY - this.offsetTop;
}
}
// clear form vars
setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 10);
});
});
};
$.fn.ajaxFormUnbind = function() {
this.unbind('submit.form-plugin');
return this.each(function() {
$(":submit,input:image", this).unbind('click.form-plugin');
});
};
$.fn.formToArray = function(semantic) {
var a = [];
if (this.length == 0) return a;
var form = this[0];
var els = semantic ? form.getElementsByTagName('*') : form.elements;
if (!els) return a;
for(var i=0, max=els.length; i < max; i++) {
var el = els[i];
var n = el.name;
if (!n) continue;
if (semantic && form.clk && el.type == "image") {
// handle image inputs on the fly when semantic == true
if(!el.disabled && form.clk == el)
a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
continue;
}
var v = $.fieldValue(el, true);
if (v && v.constructor == Array) {
for(var j=0, jmax=v.length; j < jmax; j++)
a.push({name: n, value: v[j]});
}
else if (v !== null && typeof v != 'undefined')
a.push({name: n, value: v});
}
if (!semantic && form.clk) {
// input type=='image' are not found in elements array! handle them here
var inputs = form.getElementsByTagName("input");
for(var i=0, max=inputs.length; i < max; i++) {
var input = inputs[i];
var n = input.name;
if(n && !input.disabled && input.type == "image" && form.clk == input)
a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
}
}
return a;
};
$.fn.formSerialize = function(semantic) {
return $.param(this.formToArray(semantic));
};
$.fn.fieldSerialize = function(successful) {
var a = [];
this.each(function() {
var n = this.name;
if (!n) return;
var v = $.fieldValue(this, successful);
if (v && v.constructor == Array) {
for (var i=0,max=v.length; i < max; i++)
a.push({name: n, value: v[i]});
}
else if (v !== null && typeof v != 'undefined')
a.push({name: this.name, value: v});
});
return $.param(a);
};
$.fn.fieldValue = function(successful) {
for (var val=[], i=0, max=this.length; i < max; i++) {
var el = this[i];
var v = $.fieldValue(el, successful);
if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length))
continue;
v.constructor == Array ? $.merge(val, v) : val.push(v);
}
return val;
};
$.fieldValue = function(el, successful) {
var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
if (typeof successful == 'undefined') successful = true;
if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
(t == 'checkbox' || t == 'radio') && !el.checked ||
(t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
tag == 'select' && el.selectedIndex == -1))
return null;
if (tag == 'select') {
var index = el.selectedIndex;
if (index < 0) return null;
var a = [], ops = el.options;
var one = (t == 'select-one');
var max = (one ? index+1 : ops.length);
for(var i=(one ? index : 0); i < max; i++) {
var op = ops[i];
if (op.selected) {
var v = $.browser.msie && !(op.attributes['value'].specified) ? op.text : op.value;
if (one) return v;
a.push(v);
}
}
return a;
}
return el.value;
};
$.fn.clearForm = function() {
return this.each(function() {
$('input,select,textarea', this).clearFields();
});
};
$.fn.clearFields = $.fn.clearInputs = function() {
return this.each(function() {
var t = this.type, tag = this.tagName.toLowerCase();
if (t == 'text' || t == 'password' || tag == 'textarea')
this.value = '';
else if (t == 'checkbox' || t == 'radio')
this.checked = false;
else if (tag == 'select')
this.selectedIndex = -1;
});
};
$.fn.resetForm = function() {
return this.each(function() {
if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
this.reset();
});
};
$.fn.enable = function(b) {
if (b == undefined) b = true;
return this.each(function() {
this.disabled = !b
});
};
$.fn.selected = function(select) {
if (select == undefined) select = true;
return this.each(function() {
var t = this.type;
if (t == 'checkbox' || t == 'radio')
this.checked = select;
else if (this.tagName.toLowerCase() == 'option') {
var $sel = $(this).parent('select');
if (select && $sel[0] && $sel[0].type == 'select-one') {
// deselect all other options
$sel.find('option').selected(false);
}
this.selected = select;
}
});
};
function log() {
if ($.fn.ajaxSubmit.debug && window.console && window.console.log)
window.console.log('[jquery.form] ' + Array.prototype.join.call(arguments,''));
};
})(jQuery);
</script>
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);
});
});
I have a function like this:
Session.get = function(key) {
if (!window["_SESSION"] || typeof key == 'undefined') {
return window["_SESSION"] || {};
}
if (key.indexOf('.') === -1) {
return window["_SESSION"][key] || {};
}
var keyArr = key.split('.'), val = window["_SESSION"];
for ( var i = 0; i < keyArr.length; i++) {
if (typeof val[keyArr[i]] === 'undefined') {
return null;
}
val = val[keyArr[i]];
}
return val;
}
This function allows me to get nested values without temporary variable outside of the function. Example Session.get('var.nestedvar') is returns value of window[_SESSION']['var']['nestedvar'].
Bat how can I (un)set variables like so? Tried to delete val; but didn't work.. How do the javascript references work? Does anybody know any alternative to accomplish similiar functionality?
You can delete by parent like this:
[10:00:00.380] a = {'root': {'home':'~'}}
[10:00:00.385] ({root:{home:"~"}})
--
[10:00:09.625] b = a['root']
[10:00:09.631] ({home:"~"})
--
[10:00:20.569] delete b['home']
[10:00:20.573] true
[10:00:21.684] a
[10:00:21.688] ({root:{}})
You can use a slight modification of your existing code, like this:
Session.delete = function(key) {
if (!window["_SESSION"] || typeof key == 'undefined') {
return false;
}
if (key.indexOf('.') === -1) {
if (key) {
delete key;
return true;
}
}
var keyArr = key.split('.'), val = window["_SESSION"];
var keyDepth = keyArr.length;
for ( var i = 0; i < keyDepth-1; i++) {
if (typeof val[keyDepth] === 'undefined') {
return null;
}
val = val[keyDepth];
}
if (val[keyDepth-1]) {
delete val[keyDepth-1];
return true;
}
return false;
}