基于Storage封装的支持过期时间和Json数据的临时存储

使用sessionStorage和localStorage不能直接存储json数据,需要转为字符串存储,也不支持过期时间的限制,比较不方便,现封装了一下sessionStorage和localStorage,放出来方便大家使用:

JSONStorage

changePartition(partitionName);分区存储,避免key冲突,可不切换分区
put(key,data,timeout);timeout不设置,就与sessionStorage和localStorage的过期策略一致
get(key);获取数据内容,JSON还原日期数据好像有问题,有需要可以自己改一下

var st = new JSONStorage(sessionStorage);
st.changePartition("test");
var applydata = {
	applyid : "1234",
	amount : 1234
};
st.put("1",applydata ,12);
st.remove("1");
(function(global, factory) {
	// 兼容requirejs和普通引入模式
	if (typeof module === "object" && typeof module.exports === "object") {
		module.exports = global.document ? factory(global, true) : function(w) {
			if (!w.document) {
				throw new Error("requires a window with a document");
			}
			return factory(w);
		};
	} else {
		factory(global);
	}
}(typeof window !== "undefined" ? window : this, function(window, noGlobal) {
	// 构造方法
	// 基于Storage的json存储
	var JSONStorage = function(storage) {
		this.storage = storage;
		this.partition = "";
	};
	if (typeof noGlobal === typeof undefined) {
		if (typeof window.JSONStorage === typeof undefined) {
			window.JSONStorage = JSONStorage;
		} else {
			JSONStorage = window.JSONStorage;
		}
	}

	JSONStorage.prototype.changePartition = function(partition) {
		this.partition = partition;
	};

	JSONStorage.prototype.put = function(key, value, timeout) {
		var data = {
			value : value
		};
		if (timeout) {
			if (timeout == 0) {
				this.storage.removeItem(this.partition + key);
			} else {
				data.expired_time = new Date(new Date().getTime() + timeout * 1000).getTime();
			}
		}
		this.storage.setItem(this.partition + key, JSON.stringify(data));
	};

	JSONStorage.prototype.get = function(key) {
		var data_str = this.storage.getItem(this.partition + key);
		var data = JSON.parse(data_str);
		if (data) {
			if (data.expired_time) {
				if (data.expired_time < new Date().getTime()) {
					this.storage.removeItem(this.partition + key);
					return;
				}
			}
			return data.value;
		}
	};
	
	JSONStorage.prototype.remove = function(key) {
		this.storage.removeItem(this.partition + key);
	};
	
	return JSONStorage;
}));


打赏

发表评论

电子邮件地址不会被公开。 必填项已用*标注

This site uses Akismet to reduce spam. Learn how your comment data is processed.