CHAPTER 23 OFFLINE APPLICATIONS AND CLIENT-SIDE STORAGE 之 IndexedDB

欢欢欢欢 发表于 2018-2-6 17:02

The Indexed Database API, IndexedDB for short, is a structured data store in the browser. IndexedDB came about as an alternative to the now-deprecated Web SQL Database API (not covered in this book because of its deprecated state). The idea behind IndexedDB was to create an API that easily allowed the storing and retrieval of JavaScript objects while still allowing querying and searching.

翻译:

索引数据库接口,简写IndexedDB,是一个浏览器端的结构化数据存储。IndexedDB是Web SQL数据库接口的一个替代方案,这个接口现在已经过时(由于已经过时,本书不在讨论)。IndexedDB的核心想法是创建一个接口,能简单的对JavaScript对象进行存取,同事仍旧可以查询和检索。

IndexedDB is designed to be almost completely asynchronous. As a result, most operations are performed as requests that will execute later and produce either a successful result or an error. Nearly every IndexedDB operation requires you to attach onerror and onsuccess event handlers to determine the outcome. 

翻译:

IndexedDB被设计成几乎完全异步。因此,大多数的操作都会被作为一个请求稍晚执行,并且都有可能成功或失败。几乎所有的IndexedDB操作都要求绑定错误和失败事件来处理输出。

Once fully supported, there will be a global indexedDB object that serves as the API host. While the API is still in flux, browsers are using vendor prefixes, so the object in Internet Explorer 10 is called msIndexedDB, in Firefox 4 it’s called mozIndexedDB, and in Chrome it’s called webkitIndexedDB. This section uses indexedDB in the examples for clarity, so you may need to include the following code before each example:

翻译:

如果完全支持,就会有一个全局的IndexedDB对象。然后由于该接口目前还在讨论变动中,各大浏览器厂家都使用了开发商前缀。因此,IE的用msIndexedDB,火狐的用mozIndexedDB,谷歌的用webkitIndexedDB。因此为了使用清晰,使用前需要做下兼容:

var indexedDB = window.indexedDB || window.msIndexedDB || window.mozIndexedDB || window.webkitIndexedDB;

Databases

备注:这一段已经过时。方法setVersion和属性errorCode等等,已经不可用。

IndexedDB is a database similar to databases you’ve probably used before such as MySQL or Web SQL Database. The big difference is that IndexedDB uses object stores instead of tables to keep track of data. An IndexedDB database is simply a collection of object stores grouped under a common name. 

IndexedDB和你以前使用的MySql等很相似。最大的不同就是IndexedDB使用了对象存储代替表存储。一个IndexedDB就是一个分组存储于一个共同名下的对象的集合。

 

The first step to using a database is to open it using indexedDB.open() and passing in the name of the database to open. If a database with the given name already exists, then a request is made to open it; if the database doesn’t exist, then a request is made to create and open it. The call to indexDB.open() returns an instance of IDBRequest onto which you can attach onerror and onsuccess event handlers. Here’s an example:

翻译:

使用数据库的第一步是使用indexedDB.open() 打开它打开它,传入一个要打开的数据库的名字。假如这个数据库已经存在,那么打开它;假如不存在,创建并打开它。调用indexDB.open()返回一个IDBRequest 的实例,在这个实例上面你能绑定错误或者成功事件。如下实例:

var request, database;

request = indexedDB.open(“admin”);

request.onerror = function(event){

alert(“Something bad happened while trying to open: “ + event.target.errorCode);

};

request.onsuccess = function(event){

database = event.target.result;

};

 

In both event handlers, event.target points to request, so these may be used interchangeably. If the onsuccess event handler is called, then the database instance object (IDBDatabase) is available in event.target.result and stored in the database variable. From this point on, all requests to work with the database are made through the database object itself. If an error occurs, an error code stored in event.target.errorCode indicates the nature of the problem as one of the following (these error codes apply to all operations):

翻译:

在两个事件里面,event.target指向该请求,因此他们可以被互换着使用。假如成功事件被调用,数据库实例对象(IDBDatabase)在 event.target.result被返回,并被存储在变量database中。假如错误事件被调用,一个存储在event.target.errorCode里面的错误码会指明问题所在。所有的错误码如下:

 

IDBDatabaseException.UNKNOWN_ERR (1) — The error is unexpected and doesn’t fall into an available category.

IDBDatabaseException.NON_TRANSIENT_ERR (2) — The operation is not allowed.

IDBDatabaseException.NOT_FOUND_ERR (3) — The database on which to perform the operation is not found.

IDBDatabaseException.CONSTRAINT_ERR (4) — A database constraint was violated.

IDBDatabaseException.DATA_ERR (5) — Data provided for the transaction doesn’t fulfi ll the requirements.

IDBDatabaseException.NOT_ALLOWED_ERR (6) — The operation is not allowed.

IDBDatabaseException.TRANSACTION_INACTIVE_ERR (7) — An attempt was made to reuse an already completed transaction.

IDBDatabaseException.ABORT_ERR (8) — The request was aborted and so did not succeed.

IDBDatabaseException.READ_ONLY_ERR (9) — Attempt to write or otherwise change data while in read-only mode.

IDBDatabaseException.TIMEOUT_ERR (10) — The operation could not be completed in the amount of time available.

IDBDatabaseException.QUOTA_ERR (11) — Not enough remaining disk space.

 

By default, a database has no version associated with it, so it’s a good idea to set the initial version when starting out. To do so, call the setVersion() method and pass in the version as a string. Once again, this creates a request object on which you’ll need to assign event handlers:

翻译:

一个数据库默认没有版本号,因此最好在启动它的时候给他设置一个版本号。可以通过调用方法setVersion(),传入版本号字符串实现。再次,该调用又会创建一个request对象。你需要设置处理方法。

if (database.version != “1.0”){

request = database.setVersion(“1.0”);

request.onerror = function(event){

alert(“Something bad happened while trying to set version: “ + event.target.errorCode);

};

request.onsuccess = function(event){

alert(“Database initialization complete. Database name: “ + database.name + “, Version: “ + database.version);

};

} else { alert(“Database already initialized. Database name: “ + database.name + “, Version: “ + database.version); }

 

This example tries to set the version of the database to “1.0”. The first line checks the version property to see if the database version has already been set. If not, then setVersion() is called to create the version change request. If that request is successful, then a message is displayed indicating that the version change is complete. (In a real implementation, this is where you would set up your object stores. See the next section for details.)

翻译:

上面实例视图设置数据库版本号为1.0。第一行代码检测版本号属性是否已经被设置。假如没有,那么调用setVersion()。假如请求成功,成功提示弹出。

If the database version is already “1.0”, then a message is displayed stating that the database has already been initialized. This basic pattern is how you can tell if the database you want to use has already been set up with appropriate object stores or not. Over the course of a web application, you may have many different versions of the database as you update and modify the data structures. 

翻译:

假如版本号已经是1.0了。那么会弹出一个已经设置的提示。这是一个判断数据库是否已经满足你要求的基本套路。随着频繁的使用,当你更新或修改数据库结构的时候,你可能会有很多数据库版本。