indexedDB的正确用法

indexedDB correct usage

本文关键字:用法 indexedDB      更新时间:2023-09-26

我正在试验indexedDB。现在一切都是异步的,这让我的大脑很受伤。

我创建了一个这样的对象:

var application = {};
application.indexedDB = {};
application.indexedDB.db = null;
application.indexedDB.open = function() {
   var dbName = "application";
   var dbVersion = 1;
   var openRequest = indexedDB.open(dbName, dbVersion);
   openRequest.onupgradeneeded = function(e) {
      console.log("Upgrading your DB (" + dbName + ", v" + dbVersion + ")...");
      var thisDB = e.target.result;
      if (!thisDB.objectStoreNames.contains("journal")) {
         thisDB.createObjectStore(
            "journal", 
            {keyPath: "id"}
         );
      }
   }
   openRequest.onsuccess = function(e) {
      console.log("Opened DB (" + dbName + ", v" + dbVersion + ")");
      application.indexedDB.db = e.target.result;
   }
   openRequest.onerror = function(e) {
      console.log("Error");
      console.dir(e);
   }
};

现在我可以用application.indexedDB.open()打开数据库连接了。现在我为我的对象添加了另一个功能:

application.indexedDB.addItemToTable = function(item, table) {
    var transaction = application.indexedDB.db.transaction([table], "readwrite");
    var store = transaction.objectStore(table);
    //Perform the add
    var request = store.add(item);
    request.onerror = function(e) {
        console.log("Error", e.target.error.name);
        //some type of error handler
    }
    request.onsuccess = function(e) {
        console.log("Woot! Did it");
    }
};

我的指令序列扩展如下:

  1. application.indexedDB.open()
  2. application.indexedDB.addItemToTable(item, "journal")

但这行不通。因为打开指令是异步的,所以当我在addItemToTable函数中调用application.indexedDB.db时,它还不可用。Javascript开发人员如何解决这个问题?

我在这里学习了这个教程:http://code.tutsplus.com/tutorials/working-with-indexeddb--net-34673现在我对这些例子有一些问题。

例如,他直接在"onsuccess"部分(在"Read More Data"部分)创建HTML输出。在我看来,这是糟糕的编码,因为视图与数据库读取部分无关。。不是吗?但随之而来的是我的问题。你怎么能在"成功"部分返回一些东西?添加回调函数有些复杂。尤其是当我想读取一些数据并使用该结果集获得更多数据时。描述我的意思很复杂。我做了一把小小提琴——也许它能澄清问题http://jsfiddle.net/kb8nuby6/

感谢

您不需要使用其他人的额外程序。在使用indexedDB之前,您需要了解异步javascript(AJAX)。没有办法避免它。你可以在不学习indexedDB的情况下学习AJAX。例如,看看XMLHttpRequest是如何工作的。了解setTimeout和setInterval。也许可以了解requestAnimationFrame。如果你知道nodejs的东西,请查看process.nextTick。了解函数是如何成为第一类的。了解使用回调函数的想法。了解延续传球风格。

你可能不会得到你想要的这个问题的答案。若有什么不同的话,这是关于javascript异步编程的堆栈溢出的数千个其他问题的重复。它甚至与indexedDB无关。看看关于异步js的许多其他问题。

也许这会让你开始:

var a;
setTimeout(function() { a = 1; }, 10);
console.log('The value of a is %s', a);

弄清楚为什么不起作用。如果你这样做,你将更接近于找到这个问题的答案。

我通常采用的模式是等待所有数据库操作,直到连接。它与jQuery中的$.ready概念相似。

你会发现,随着应用程序的老化,你有很多架构版本,也需要升级数据。数据库连接本身有很多逻辑。

若需要在准备好之前使用数据库,则可以使用回调队列。以下是谷歌关于推荐队列的分析片段:

// Creates an initial ga() function.  The queued commands will be executed once analytics.js loads.
i[r] = i[r] || function() {
  (i[r].q = i[r].q || []).push(arguments)
},

基本上,一旦连接了数据库,就会执行这些回调。

我强烈建议你去看看我自己的图书馆,ydn-db。它有所有这些概念。