我试图重构我编写的使用IndexedDb的代码。理想情况下,我想做的是创建一个小型业务库,该库抽象出使用IndexedDb的某些丑陋之处。因此,例如,我将创建一个toDoList对象,该对象将具有一些用于Get,Add,Update,Delete的方法,在这些方法中,我将调用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);


问题是在get方法中未定义MyApp.db,因为尚未成功调用onsuccess回调。我对javascript还是很陌生,所以想知道我可以使用哪些选项/模式。谢谢你的帮助!

最佳答案

可能有1000种不同的方法来处理此问题。但是我建议您在“ get”方法中简单地包含一个失败选项,如果数据库尚未准备就绪,则可以触发该选项:

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


您还应该考虑为客户端提供一种回调方法,以便确定数据库何时准备就绪(或不准备就绪)。如果没有其他要求,至少可以为他们提供某种方式,以便他们通过一种方法轻松检查数据库是否已准备就绪。根据您希望向用户展示该工具的方式,您可以使用许多选项。

10-07 19:05
查看更多