var _storage = { /* 5 */ data: {}, getPath: function(path, otherwise){ var keys = path.slice(0); var key = keys.shift(); if (this.data.hasOwnProperty(key)) { var objValue = this.data[key]; for (var index in keys) { var subKey = keys[index]; if (isObject(objValue) && objValue.hasOwnProperty(subKey)) { objValue = objValue[subKey]; } else { return otherwise; } } return objValue; } else { return otherwise; } }, get: function(key, otherwise){ if (isArray(key)) return this.getPath(key, otherwise); var value = this.data.hasOwnProperty(key) ? this.data[key] : otherwise; return value; }, savePath: function(path, value){ var keys = path.slice(0); var key = keys.shift(); var subValue, objValue = subValue = !this.data.hasOwnProperty(key) ? {} : isObject(this.get(key)) ? this.get(key) : { '\\0': this.get(key) } ; for (var index in keys) { var subKey = keys[index]; if (subKey === '') subKey = '\'\''; else if (!isString(subKey)) subKey = new String(keys[index]).toString(); if (keys.length == +index + 1) { subValue[subKey] = value; } else { if (!isObject(subValue[subKey])) { subValue[subKey] = { '\\0': subValue[subKey] }; } subValue = subValue[subKey]; } } return this.save(key, objValue); }, save: function(key, value){ if (isArray(key)) return this.savePath(key, value); var jsonValue = JSON.stringify(value); localStorage.setItem(key, jsonValue); return this; }, removePath: function(path){ var keys = path.slice(0); var key = keys.shift(); var subValue, objValue = subValue = this.get(key); for (var index in keys) { var subKey = keys[index]; if (isObject(subValue) && subValue.hasOwnProperty(subKey)) { if (keys.length == +index + 1) { delete subValue[subKey]; } else { subValue = subValue[subKey]; } } else { return false; } } return this.save(key, objValue); }, remove: function(key){ if (isArray(key)) return this.removePath(key); localStorage.removeItem(key); return this; }, update: function(){ //console.log('localStorage', [localStorage]); for (var key in localStorage) { var jsonValue = localStorage.getItem(key); var value; try { value = JSON.parse(jsonValue); } catch (e) { value = jsonValue; } this.data[key] = value; } return this; }, observables: {}, observable: function(path, defaultValue){ var name = new String(path).toString(); var koObservable = this.observables[name] = ko.observable(this.get(path, defaultValue)); koObservable.subscribe(function(value){ _storage.save(path, value); }); return koObservable; } }.update(); //c('{storage}', _storage.data);