H 5 js処理localstorageメソッドパッケージ

1891 ワード

/*
  localstorage              ,              ,                。             。
*/
var mystorage = (function mystorage(){
    var ms = "mystorage";
    var storage=window.localStorage;
    if(!window.localStorage){
        alert("     localstorage");
        return false;
    }

    var set = function(key,value){
        //  
        var mydata = storage.getItem(ms);
        if(!mydata){
            this.init();
            mydata = storage.getItem(ms);
        }
        mydata = JSON.parse(mydata);
        mydata.data[key] = value;
        storage.setItem(ms,JSON.stringify(mydata));
        return mydata.data;

    };

    var get = function(key){
        //  
        var mydata = storage.getItem(ms);
        if(!mydata){
            return false;
        }
        mydata = JSON.parse(mydata);

        return mydata.data[key];
    };

    var remove = function(key){
        //  
        var mydata = storage.getItem(ms);
        if(!mydata){
            return false;
        }

        mydata = JSON.parse(mydata);
        delete mydata.data[key];
        storage.setItem(ms,JSON.stringify(mydata));
        return mydata.data;
    };

    var clear = function(){
        //    
        storage.removeItem(ms);
    };

    var init = function(){
        storage.setItem(ms,'{"data":{}}');
    };

    return {
        set : set,
        get : get,
        remove : remove,
        init : init,
        clear : clear
    };



})();


console.log(mystorage.set('tqtest','tqtestcontent'));//  
console.log(mystorage.set('tqtest1','tqtestcontent1'));//  
console.log(mystorage.set('tqtest1','newtqtestcontent1'));//  
console.log(mystorage.get('tqtest'));//  
console.log(mystorage.remove('tqtest'));//  
mystorage.clear();//    

/*
                    。
 */