IndexedDB 工具类

var dbUtil = function () {

    var dbInfo={
        dbName:"Wei_You_DB",  // 名称
        dbVersion:"1.0"// 版本
    };
    var $this = this;
    var db;
    var indexedDB = window.indexedDB || window.webkitIndexedDB;

    if ('webkitIndexedDB' in window) {
        window.IDBTransaction = window.webkitIDBTransaction;
        window.IDBKeyRange = window.webkitIDBKeyRange;
    }

    function createDB_And_InitTables(objectStores,successCallBack,failedCallback){

        if(!objectStores || objectStores.length==0) return;

        var request = indexedDB.open(dbInfo.dbName);
        request.onsuccess = function(evt) {
            db = evt.target.result;
            // 只能在 setVersion 事务中创建 Object Stores;
            if (dbInfo.dbVersion!= db.version) {
                var setVReq = db.setVersion(dbInfo.dbVersion);
                // onsuccess 方法是唯一创建 Object Stores 的地方
                setVReq.onerror = dbError;
                setVReq.onsuccess = function() {
                    if(typeof objectStores == "string"){
                        if(!db.objectStoreNames.contains(objectStores)) {
//                            db.deleteObjectStore("ShoppingCart");
                            db.createObjectStore(objectStores,{keyPath: "id"});
                        }
                        return;
                    }
                    if(objectStores instanceof Array){
                        for(var i=0; i<objectStores.length ;i++){
                            if(!db.objectStoreNames.contains(objectStores[i])) {
//                            db.deleteObjectStore("ShoppingCart");
                                db.createObjectStore(objectStores[i],{keyPath: "id"});
                            }
                        }
                    }
                    successCallBack();
                };
            }
            else{
                successCallBack();
            }
        };
        request.onerror = failedCallback || function(e){
            console.error("exec createDB_And_InitTables error cause:"+ e.message);
        };
    }
    //插入或更新数据
    function insertOrUpdateData(data,objectStoreName,successCallBack,failedCallback){
        if(!data || !objectStoreName) return false;
        var trans = db.transaction([objectStoreName], IDBTransaction.READ_WRITE);
        var store = trans.objectStore(objectStoreName);
        var request = store.put(data);
        request.onsuccess = successCallBack;
        request.onerror = failedCallback;
    }
    function dbError(error){
        console.error(error);
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值