2012-09-06 44 views
0

我想重構一些我使用IndexedDb編寫的代碼。理想情況下,我想要做的是創建一個小型商業圖書館,該圖書館可以抽象出使用IndexedDb的一些醜陋之處。因此,例如,我將創建一個toDoList對象,該對象將具有一些方法來獲取,添加,更新,刪除,並在這些方法中我將調用IndexedDb。引用屬性設置爲異步

這裏是什麼,我有一個例子:

var MyApp = MyApp || {}; 

(function() { 

    var req = indexedDB.open("todostore", 1); 

    req.onerror = function(e) { console.log(e); }; 

    req.onupgradeneeded = function (e) { 
    var newDB = e.target.result; 
    newDB.createObjectStore("todostore", { keyPath : "id", autoIncrement : true }); 
    }; 

    req.onsuccess = function() { 
    MyApp.db = req.result; 
    }; 

})(); 

MyApp.todolist = (function() { 
    return { 
    get : function(key, success) { 
     var tran = MyApp.db.transaction("todostore"); 
     var req = tran.objectStore("todostore").get(key); 

     req.onsuccess = function (e) {   
     success(e.target.result); 
     }; 
    } 
    }; 
})(); 

//consumer of library would ideally just do something like this: 

var worked = function(e) { 
    //do something... 
} 
MyApp.todolist.get(1, worked); 

問題是MyApp.db在GET方法不確定,因爲回調的onSuccess尚未觸發。我對JavaScript仍然陌生,所以想知道我可以使用哪些選項/模式。謝謝你的幫助!

回答

2

可能有1000種不同的方式來處理這個問題。不過,我會建議只是包括在你的「得到」的方法失敗時的選項,並有觸發如果數據庫是沒有準備好:

MyApp.todolist = (function() { 
    return { 
    get : function(key, success, failure) { 
     if(!MyApp.db) { 
     if(typeof failure === "function") { 
      failure("Database is not ready yet"); 
     } 
     return; 
     } 
     var tran = MyApp.db.transaction("todostore"); 
     var req = tran.objectStore("todostore").get(key); 

     req.onsuccess = function (e) {   
     success(e.target.result); 
     }; 
    } 
    }; 
})(); 

//consumer of library would ideally just do something like this: 

var worked = function(e) { 
    //do something... 
}; 

var didntWork = function(e) { 
    //report the error, e. 
}; 

MyApp.todolist.get(1, worked, didntWork); 

你也應該考慮提供一個回調方法爲你的客戶利用到確定數據庫何時準備好(或不準備)。如果沒有別的,至少可以提供一些方法讓他們通過方法輕鬆檢查數據庫是否準備就緒。根據您希望向用戶展示該工具的方式,您可以使用許多選項。

+0

「您還應該考慮爲客戶提供一種回調方法,以便確定數據庫何時準備好(或不準備)。」我認爲這是更好的解決方案。如果你知道你會遇到需要等待數據庫準備就緒的情況,那麼你也可以處理它。異步代碼是混亂和醜陋的,但是從長遠來看,試圖忽略IndexedDB的異步性質更糟糕。 – dumbmatter

+0

我的心理障礙是關於如何「等待」db被設置,然後繼續w/flow,並且你的回答讓我在那裏,所以謝謝。我最終添加了一個init方法,承諾等待數據庫初始化,然後繼續保持應用程序流。 –