【问题标题】:How to convert the data into different types when retrieving from local storage从本地存储中检索时如何将数据转换为不同的类型
【发布时间】:2015-10-29 05:32:38
【问题描述】:

我正在编写一个小库来操作 localStorage 中的数据。

下面是sn-p的代码:

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) 下面的代码sn-p能否进一步改进。

【问题讨论】:

  • 我猜你是在本地存储中存储对象?如果是这样,它们当然是字符串。您可以为每个存储的包含数据类型的数据添加另一个键,然后在 get() 方法中将其转换为正确的类型。
  • 1) 尝试推送格式为{type: 'mytype', data: 'mydata_ofmytype'} 的对象,以便您始终可以知道所代表的类型。 2)为了什么目标进一步改进???这样的问题是??????
  • 进一步改进是指代码在代码质量和设计方面如何进一步改进@morels

标签: javascript json html local-storage web-storage


【解决方案1】:

希望有所帮助!

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);

【讨论】:

  • +1 为答案。但它会在最新的 chrome 控制台中抛出 Uncaught TypeError: window.localStorage.bind is not a function
  • 我已经进行了重构,所以现在可以正常工作了,希望你能接受我的回答!
猜你喜欢
  • 1970-01-01
  • 2014-09-01
  • 2016-04-02
  • 1970-01-01
  • 2016-10-29
  • 2020-08-21
  • 2018-04-26
  • 1970-01-01
  • 2018-10-12
相关资源
最近更新 更多