我使用IndexedDB,Web SQL或Web Storage在客戶端上存儲一些數據(或者在客戶端不支持任何存儲的情況下回退到AJAX)。加載頁面時,我想顯示商店中的一些數據。但是當DOM準備就緒時,我無法顯示數據,因爲商店可能沒有準備好,並且當商店準備就緒時我無法顯示數據,因爲DOM可能沒有準備好。如何激發取決於2(或更多)條件的JS事件
很明顯,我可以實現一些條件,檢查由dom和商店設置的標誌,或者我可以使用超時但看起來馬虎(如果超過2個條件需要滿足,將不能很好地擴展)。是否有一種「良好」的方式來處理這種情況?我寧願使用跨瀏覽器解決方案(例如watch
將不起作用)。的情況
例子:
// FooServiceFactory decides which storage method to use based on
// what the browser allows and returns a new instance of the
// implementation and starts initializing resources.
var fooService = FooServiceFactory.getInstance();
// DOM is ready
window.onload = function() {
// fooService may not be ready yet depending on whether
// storage has already been setup or if resources need to
// be retrieved from the server. But I don't want this calling
// JS to know about that.
fooService.getAllFoo(request, function(response, status) {
// do something with response
});
};
注:我接受我自己的答案,現在,但我仍然是開放的處理這個更好的方法。
爲什麼你認爲檢查條件標誌是否兩者都準備好是sl?不馴?這對我來說似乎相當合乎邏輯。 – Matt
@Matt,我的存儲隱藏在服務層後面。雖然肯定會有效,但有標誌會破壞[封裝](http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29)。我不希望該服務知道DOM,並且我不希望調用JS知道它必須設置的全局變量,如果我可以幫助的話。 –
@Matt,我用一個例子更新了我的問題。 –