forked from 0x2620/oxjs
add localStorage to polyfills; slightly refactor Ox.localStorage; remove whitespace; update example
This commit is contained in:
parent
41a3eaacd4
commit
5b6f161612
3 changed files with 74 additions and 28 deletions
|
|
@ -97,13 +97,54 @@ My.range = function() {
|
|||
return a;
|
||||
};
|
||||
|
||||
|
||||
My.foo = {
|
||||
array: [
|
||||
{a: 1, b: 2},
|
||||
{c: 3, d: 4}
|
||||
],
|
||||
objects: {
|
||||
|
||||
/*@
|
||||
My.localStorage <f> Returns a localStorage handler for a given namespace
|
||||
(ns) -> storage <f> localStorage handler
|
||||
() -> <o> Returns all key:value pairs
|
||||
(key) -> <*> Returns one value
|
||||
(key, value) -> <f> Sets one value, returns the handler
|
||||
({key: value, ...}) -> <f> Sets one or more values, returns the handler
|
||||
key <s> Any string
|
||||
value <*> Any value that can be JSON-serialized
|
||||
.delete <f> Delete method
|
||||
() -> <f> Deletes all key:value pairs, returns the handler
|
||||
(key[, ...]) -> <f> Deletes one or more pairs, returns the handler
|
||||
key <s> Any string
|
||||
ns <s> Namespace
|
||||
*/
|
||||
My.localStorage = (function() {
|
||||
if (!window.localStorage) {
|
||||
window.localStorage = {};
|
||||
}
|
||||
}
|
||||
return function(ns) {
|
||||
function storage(key, value) {
|
||||
var args, ret;
|
||||
if (arguments.length == 0) {
|
||||
ret = {};
|
||||
Ox.forEach(localStorage, function(value, key) {
|
||||
if (Ox.startsWith(key, ns + '.')) {
|
||||
ret[key.slice(ns.length + 1)] = JSON.parse(value);
|
||||
}
|
||||
});
|
||||
} else if (arguments.length == 1 && typeof key == 'string') {
|
||||
value = localStorage[ns + '.' + key];
|
||||
ret = Ox.isUndefined(value) ? void 0 : JSON.parse(value);
|
||||
} else {
|
||||
Ox.forEach(Ox.makeObject(arguments), function(value, key) {
|
||||
localStorage[ns + '.' + key] = JSON.stringify(value);
|
||||
});
|
||||
ret = this;
|
||||
}
|
||||
return ret;
|
||||
};
|
||||
storage.delete = function() {
|
||||
var keys = arguments.length == 0 ? Object.keys(storage())
|
||||
: Ox.toArray(arguments)
|
||||
keys.forEach(function(key) {
|
||||
delete localStorage[ns + '.' + key];
|
||||
});
|
||||
return storage;
|
||||
};
|
||||
return storage;
|
||||
};
|
||||
}();
|
||||
Loading…
Add table
Add a link
Reference in a new issue