0
    this.init = function (onupgradeneeded, onsuccess) {

        var openRequest = indexedDB.open(dbName);

        openRequest.onupgradeneeded = function (e) {

            db = e.target.result;

            if (!db.objectStoreNames.contains(objectStoreName)) {

                console.log('Creating the ' + objectStoreName + ' objectstore');

                db.createObjectStore(objectStoreName, { keyPath: "id", autoIncrement: true });

            }

        };

        openRequest.onsuccess = function (e) {

            db = e.target.result;

            db.onerror = function (event) {
                // Generic error handler for all errors targeted at this database requests
                console.log("Database error: " + event.target.errorCode);
            };
        };

    };

调用者:

var idb = new Demo.IndexedDB();
idb.init();

openRequest.onupgradeneeded当 init 函数运行时,它要么以要么结束openRequest.onsuccess

我想知道的是是否有可能创建一个在两个函数中都被调用的通用回调函数。因此,无论运行两个函数中的哪一个,我都可以通过使用知道它们何时完成

idb.init(function(){
    //onupgradeneeded or onsuccess completed
});

希望你明白这个想法,否则会详细说明。

谢谢

4

1 回答 1

4

只需传入一个回调函数并在两种情况下调用一个回调:

this.init = function (onFinish) {

    var openRequest = indexedDB.open(dbName);

    openRequest.onupgradeneeded = function (e) {

        db = e.target.result;

        if (!db.objectStoreNames.contains(objectStoreName)) {

            console.log('Creating the ' + objectStoreName + ' objectstore');

            db.createObjectStore(objectStoreName, { keyPath: "id", autoIncrement: true });

        }
        onFinish();

    };

    openRequest.onsuccess = function (e) {

        db = e.target.result;

        db.onerror = function (event) {
            // Generic error handler for all errors targeted at this database requests
            console.log("Database error: " + event.target.errorCode);
        };
        onFinish();
    };

};
于 2012-08-11T23:47:42.233 回答