引用设置为异步的属性

时间:2012-09-06 03:43:23

标签: javascript indexeddb

我正在尝试重构我编写的一些使用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的新手,所以想知道我可以使用哪些选项/模式。谢谢你的帮助!

1 个答案:

答案 0 :(得分:2)

可能有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);

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