我正在编写一个小库来操作localStorage中的数据。
以下是代码段:
function AppStorage (appName) {
"use strict";
var prefix = appName;
var saveItem = function (key, value) {
if (!key || !value) {
console.error("Missing parameters \"key\" and \"value\"");
return false;
}
if (window.localStorage && window['localStorage']) {
try {
if (typeof value === 'Object') localStorage.setItem(prefix + '_' + key, JSON.stringify(value));
if (typeof value === 'string') localStorage.setItem(prefix + '_' + key, value);
return true;
} catch (e) {
return false;
}
} else {
return false;
}
}
var getItem = function (key) {
if (!key) {
console.error("Missing parameter \"key\"");
return false;
}
if (window.localStorage && window['localStorage']) {
try {
return localStorage.getItem(prefix + '_' + key);
} catch (e) {
return false;
}
} else {
return false;
}
}
var removeItem = function (key) {
if (!key) {
console.error("Missing parameter \"key\"");
return false;
}
if (window.localStorage && window['localStorage']) {
try {
localStorage.removeItem(prefix + '_' + key);
return true;
} catch (e) {
return false;
}
} else {
console.log("Browser does not support HTML5 Web Storage");
}
}
return {
set: function (key, value) {
return saveItem(key, value);
},
get: function (key) {
return getItem(key);
},
remove: function (key) {
return removeItem(key);
}
}
}
var as = new AppStorage ('MyApp');
我如何坚持以下两个问题。
1)当通过get()
检索数据时,存储的信息将作为string
返回。我需要在传递之前以相同的格式接收这些信息。
2)可以进一步改进以下代码片段。
答案 0 :(得分:3)
var ClientStorageService = (function(persistent, session) {
if(!persistent && !session) {
throw new Error('ClientStorage Not Suppoerted');
}
function ClientStorage() {};
ClientStorage.prototype.driver = persistent || session;
ClientStorage.prototype.prefix = 'HELLOWORLD_';
ClientStorage.prototype.usePersistent = function() {
if(persistent) {
this.driver = persistent;
return true;
}
return false;
};
ClientStorage.prototype.useSession = function() {
if(session) {
this.driver = session;
return true;
}
return false;
};
ClientStorage.prototype.read = function(key) {
key = this.prefix + key;
var data = this.driver.getItem(key);
if(data) {
try {
data = JSON.parse(data);
} catch(e) {}
return data;
}
return null;
};
ClientStorage.prototype.store = function(key, val) {
key = this.prefix + key.toString();
try {
val = JSON.stringify(val);
} catch(e) {}
this.driver.setItem(key, val);
return this;
};
ClientStorage.prototype.clear = function(key) {
var task = 'clear';
if(key) {
key = this.prefix + key;
task = 'removeItem';
}
this.driver[task](key);
};
return new ClientStorage();
})(window.localStorage, window.sessionStorage);
ClientStorageService.store('FOO', { greetings: 'Hello World' });
var result = ClientStorageService.read('FOO');
console.log('result is', result);