2012-08-11 248 views
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); 
      }; 
     }; 

    }; 

被調用。通用異步回調函數

我想知道的是,如果它可能創建一個通用的回調函數,在函數中調用。所以不管哪兩個功能的運行,我可以知道什麼時候嗎更有用

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

希望你的想法做,否則生病闡述。

感謝

+0

只是要'.init'接受一個參數,調用回調都傳入的參數。 – 2012-08-11 23:46:10

+0

@FelixKling剛剛注意到。有時它比你想象的更容易:-)謝謝 – Johan 2012-08-11 23:47:30

回答

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(); 
    }; 

}; 
+0

謝謝。有時它比你想象的更容易:-) – Johan 2012-08-11 23:50:01