2012-09-06 42 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方法,承诺等待数据库初始化,然后继续保持应用程序流。 –