简单使用IndexedDB

23 1 月

因为项目的需求,简单的研究了下IndexedDB,只实现简单的读取和写入

代码如下:

(function(){
	var db;
	var v;

	var request = indexedDB.open("ecmascriptdb", 1);
	request.onerror = function(event) {
		alert('error!');
	};
	request.onsuccess = function(e) {
		db = request.result;

		window.set_data = function(name, value) {		
			var trans = db.transaction(["history"],"readwrite"); 
			var store = trans.objectStore("history");				
			var request = store.get(name);
			request.onsuccess = function() {
				// grab the data object returned as the result
				var data = request.result;
				if (data){
					data.value = value;
					store.put(data);
				}else{
					store.add({key:name,value:value});
				}
			};
		}

		window.get_data = function(name, callback) {
			var trans = db.transaction("history"); 
			var store = trans.objectStore("history");
			var request = store.get(name);
			request.onerror = function(event) {
				callback(null);
			};
			request.onsuccess = function(event) {
				var data = request.result;
				if (!data) callback(null);
				else callback(data.value);
			};
		}

	}

	request.onupgradeneeded = function(event) { 
		var db = event.target.result;

		db.onerror = function(event) {

		};

		var objectStore = db.createObjectStore("history", { keyPath: "key" });

		objectStore.createIndex("value", "value", { unique: false });
	};
})();

之后发现了localStorage这个东东,简单许多,这个项目果断放弃了IndexedDB,相同的封装代码如下:

if (window.localStorage){
	window.set_cookie = function(name, value) {
		window.localStorage.setItem(name, value);
	}

	window.get_cookie = function(name, callback) {
		callback(window.localStorage.getItem(name));
	}
}

 

参考资料:

IndexedDB: https://developer.mozilla.org/en-US/docs/IndexedDB/Using_IndexedDB

localStorage: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage

发表回复

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