`

indexeddb

阅读更多

 

这里有indexeddb的一些使用,各种操作基本都包括,有的被注释

 

var key = null;

            // Simply open the database once so that it is created with the required tables

            $.indexedDB("MyECommerceSite", {

            "schema": {

            "1": function(versionTransaction){

            var catalog = versionTransaction.createObjectStore("catalog", {

            "keyPath": "itemId"

            });

            catalog.createIndex("price");

            },

            // This was added in the next version of the site

            "2": function(versionTransaction){

            var cart = versionTransaction.createObjectStore("cart", {

            "autoIncrement": true

            });

            cart.createIndex("itemId");

            var wishlist = versionTransaction.createObjectStore("wishlist", {

            "autoIncrement": false,

            "keyPath": "itemId"

            });

            wishlist.createIndex("name");

            }

            }

            }).done(function(){

            // Once the DB is opened with the object stores set up, show data from all tables

            window.setTimeout(function(){

            loadFromDB("cart");

            loadFromDB("wishlist");

            downloadCatalog();

            }, 200);

            });

 

            $.indexedDB("www.huffmans.cn", {

            "schema": {

            "1": function(versionTransaction){

            var oflb = versionTransaction.createObjectStore("oflb", {

            //"keyPath": "name",

            //"autoIncrement": true  //do pk

            });

            oflb.createIndex("name"); //support mutiples index

            }

            }

            }).done(function(){

            // Once the DB is opened with the object stores set up, show data from all tables

            window.setTimeout(function(){

            //loadFromDB("cart");

            //loadFromDB("wishlist");

            //downloadCatalog();

            downloadxml();

            //setTimeout(loadFromOflb('oflb'),200);

            //updoflb2('oflb');

            //loadFromOflb('oflb');

            usedbidx();

            }, 200);

            });

 

            function downloadxml(){

            var setting = {

            url:'<%=basePath%>github/indexdb/tdata/catalog.json',

            type:'get',dataType:'json',async:false,

            success:function(data){

            $.indexedDB('www.huffmans.cn').transaction('oflb').then(function(){//*READ_ONLY* ,*READ_WRITE* // 0 or 1 

            console.log("Transaction completed, all data inserted  ===");

            //loadFromDB("catalog");

            }, function(err, e){

            console.log("Transaction NOT completed ===", err, e);

            },function(transaction){

            var oflb = transaction.objectStore('oflb'); 

            $.each(data,function(){

            //alert(JSON.stringify(this));

            oflb.add(this,this.name);

            });

            oflb.put({  // is not update

"itemId": 10012,

"name": "ljdd",

"description": "Asd normal looking desktop computer",

"price": 10022,

"rating": 222

},'Desktop');

            });},

            error:function(xhr,ts,et){alert(et);}

            };

            $.ajax(setting);

            }

 

            function loadFromOflb(table){

$.indexedDB("www.huffmans.cn").objectStore(table).get('Desktop').then(function(data){

alert(JSON.stringify(data));

});

            /*

            $.indexedDB("www.huffmans.cn").objectStore(table).each(function(elem){

            //addRowInHTMLTable(table, elem.key, elem.value);

            console.log(elem.key+':'+elem.value);

            });

            * */

            }

            function updoflb(table){

            $.indexedDB("www.huffmans.cn").objectStore(table).put({

"itemId": 1001,

"name": "lj",

"description": "A normal looking desktop computer",

"price": 100,

"rating": 2

},'Desktop').done(function(result, event){

//result; // Result of the operation. Some operations like delete will return undefined

//event; // Success Event

alert('==');

//if(event){alert('oks');}

}

).fail(function(error, event){

alert(error);

//error; // Type of error that has occured

//event; // Error event

//event.type; // indicates if there was an error or an exception

});

            }

 

            function updoflb2(table){

            //$.indexedDB("www.huffmans.cn").objectStore(table).delete('Desktop');

            //$.indexedDB("www.huffmans.cn").objectStore(table).add('Desktop',{'name':'lij'});

            $.indexedDB('www.huffmans.cn').transaction('oflb').then(function(){

            console.log("Transaction completed, all data inserted  ===");

            //loadFromDB("catalog");

            }, function(err, e){

            console.log("Transaction NOT completed ===", err, e);

            },function(transaction){

            var oflb = transaction.objectStore('oflb');

            //$.each(data,function(){

            //alert(JSON.stringify(this));

            oflb.put({  // is not update

"itemId": 10012,

"name": "ljdd",

"description": "Asd normal looking desktop computer",

"price": 10022,

"rating": 222

},'lj');

            //});

            });

            /*

            $.indexedDB("www.huffmans.cn").objectStore(table).each(function(data){

//alert(JSON.stringify(data));

if(data.key=='Desktop')

data.update({

"itemId": 10012,

"name": "lj",

"description": "Asd normal looking desktop computer",

"price": 10022,

"rating": 222

});

});

            * */

            }

 

            function usedbidx(){

            $.indexedDB('www.huffmans.cn').transaction('oflb').then(function(){//*READ_ONLY* ,*READ_WRITE* // 0 or 1 

            console.log("Transaction completed, all data inserted  ===");

            //loadFromDB("catalog");

            }, function(err, e){

            console.log("Transaction NOT completed ===", err, e);

            },function(transaction){

            transaction.objectStore('oflb').count().done(function(result,event){alert(result);}); // total is result

           

            //alert($(oflbc).length);

            transaction.objectStore('oflb').clear();//.done(function(result,event){alert(result);});

            //oflbc = transaction.objectStore('oflb').count();

           

            //alert(transaction.objectStore('oflb').count());

            var oflb = transaction.objectStore('oflb').index('name').eachKey(function(item){  //each fn include :k,v

            //console.log(item+'<<');//+'<<'+item.key);

            }); 

           

            /*

            $.each(data,function(){

            //alert(JSON.stringify(this));

            oflb.add(this,this.name);

            });

            oflb.put({  // is not update

"itemId": 10012,

"name": "ljdd",

"description": "Asd normal looking desktop computer",

"price": 10022,

"rating": 222

},'Desktop');

            * */

            });

            }

            function deleteDB(){

            // Delete the database 

            $.indexedDB("MyECommerceSite").deleteDatabase();

            }

 

            // Download a catalog from the server and save it to the DB

            function downloadCatalog(){

            $.getJSON("<%=basePath%>github/indexdb/tdata/catalog.json", function(data){

            $.indexedDB("MyECommerceSite").transaction("catalog").then(function(){

            console.log("Transaction completed, all data inserted");

            loadFromDB("catalog");

            }, function(err, e){

            console.log("Transaction NOT completed", err, e);

            }, function(transaction){

            var catalog = transaction.objectStore("catalog");

            catalog.clear();

            $.each(data, function(i){

            _(catalog.add(this));

            })

            });

            });

            }

 

            // Iterate over each record in a table and display it

            function loadFromDB(table){

            //emptyTable(table);

            _($.indexedDB("MyECommerceSite").objectStore(table).each(function(elem){

            //addRowInHTMLTable(table, elem.key, elem.value);

            }));

            }

            function updoflib(table){

            $.indexedDB("MyECommerceSite").objectStore(table)

            }

 

            // Sort a table based on an index that is setup

            function sort(table, key){

            //emptyTable(table);

            _($.indexedDB("MyECommerceSite").objectStore(table).index(key).each(function(elem){

            //addRowInHTMLTable(table, elem.key, elem.value);

            }));

            }

 

            function emptyDB(table){

            _($.indexedDB("MyECommerceSite").objectStore(table).clear());

            }

 

            // Read an item from catalog and save it in cart

            function addToCart(itemId){

            $.indexedDB("MyECommerceSite").objectStore("catalog").get(itemId).then(function(item){

            $.indexedDB("MyECommerceSite").objectStore("cart").add(item).done(function(){

            loadFromDB("cart");

            });

            }, function(err, e){

            alert("Could not add to cart");

            });

            }

 

            // Delete an item from cart

            function removeFromCart(itemId){

            $.indexedDB("MyECommerceSite").objectStore("cart")["delete"](itemId).done(function(){

            loadFromDB("cart");

            });

            }

 

            // Using transactions, read object from cart, add it to wishlist if it does not exist 

            // and then delete it from the cart. If any operation failes, all these will fail

            function moveToWishlist(cartId){

            var transaction = $.indexedDB("MyECommerceSite").transaction(["cart", "wishlist"]);

            transaction.done(function(){

            loadFromDB("cart");

            loadFromDB("wishlist");

            });

            transaction.progress(function(transaction){

            transaction.objectStore("cart").get(cartId).done(function(item){

            transaction.objectStore("wishlist").add(item).fail(function(){

            alert("Already in the wishlist");

            }).done(function(){

            _(transaction.objectStore("cart")["delete"](cartId));

            });

           

            })

            });

            }

 

            // Read an item from catalog and add it to wishlist

            function addToWishlist(itemId){

            $.indexedDB("MyECommerceSite").objectStore("catalog").get(itemId).then(function(item){

            $.indexedDB("MyECommerceSite").objectStore("wishlist").add(item).done(function(){

            loadFromDB("wishlist");

            })

            }, function(err, e){

            alert("Could not add to cart");

            });

            }

 

            function removeFromWishList(itemId){

            $.indexedDB("MyECommerceSite").objectStore("wishlist")["delete"](itemId).done(function(){

            loadFromDB("wishlist");

            });

            }

 

            function renderJSON(val){

            var result = [];

            for (var key in val) {

            result.push("<div class = 'keyval'>");

            result.push("<span class = 'key'>", key, "</span>");

            result.push("<span class = 'value'>", JSON.stringify(val[key]), "</span>");

            result.push("</div>")

            }

            return result.join("");

            }

 

            function _(promise){

            promise.then(function(a, e){

            console.log("Action completed", e.type, a, e);

            }, function(a, e){

            console.log("Action completed", a, e);

            }, function(a, e){

            console.log("Action completed", a, e);

            })

            }

 

 

##########

 

catalog.json

 

 

[{

"itemId": 1001,

"name": "Desktop",

"description": "A normal looking desktop computer",

"price": 100,

"rating": 2

 

}, {

"itemId": 1002,

"name": "Laptop",

"description": "A laptop computer",

"price": 200,

"rating": 4

}, {

"itemId": 1003,

"name": "Tablet",

"description": "A tablet computer",

"price": 150,

"stock": 4

}, {

"itemId": 1004,

"name": "Embedded",

"description": "Whatever",

"stock": 4

}, {

"itemId": 1005,

"name": "EInk Reader",

"description": "Like a tablet, but different screen",

"price": 150,

"stock": 4

}, {

"itemId": 1006,

"name": "Phone",

"description": "No more a computer",

"price": 250,

"stock": 4

}, {

"itemId": 1007,

"name": "Music players",

"description": "the outer imits ? ",

"price": 10,

"stock": 4

}]


##########

官方api

 

Jquery-IndexedDB API Reference
===============================

List of APIs - Quick Reference

* [$.indexedDB()] (#openDatabase)
* [$.indexedDB(, schema)] (#openDatabaseUpgrade)
* [$.indexedDB().transaction()] (#transactionSec)
* [$.indexedDB().objectStore()] (#objectStore)
* [$.indexedDB().objectStore().add()] (#crud)
* [$.indexedDB().objectStore().each()] (#cursorEach)
* [$.indexedDB().objectStore().index()] (#index)
* [$.indexedDB().objectStore().deleteDatabase()] (#deleteDatabase) 

IndexedDB - Quick Intro
-------------------------
* [IndexedDB] (http://www.w3.org/TR/IndexedDB/) is a database inside a browser to save and retrieve objects on the browser/client.
* IndexedDB contains multiple `objectStores` (sort of tables) that contain data. 
	*  `objectStores` have data records in form of (key, javascript object) pairs. (key) uniquely identify records
	* Data can be written to, read from, or iterated over, inside and `object store`
	* (key, javascript object) pairs can also have indexes on a property in the (javascript object)
* Data operations can be scoped into transactions. 

Open Database <a name = "openDatabase"/>
----------------------------------------
Creates a new connection to the _Indexed Database_ specified as the name. 

``` javascript
var dbOpenPromise = $.indexedDB("database_name", { 
	// The second parameter is optional
	"version" : 3,  // Integer version that the DB should be opened with
	"upgrade" : function(transaction){
		// Function called when DB is of lower version that specified in the version parameter
		// See transaction for details on the argument
	},
	"schema" : {
		"1" : function(transaction){
			// List of instructions to run when DB version is upgraded to 1. 
			// See transaction for details on the argument
		},
		"2" : function(transaction){
			// Examples of using the transaction object
			var obj1 = transaction.objectStore("store1");
			var obj2 = transaction.createObjectStore(store2);
			obj1.createIndex("index");
		}
	}
});
```

<a name = "openDatabaseUpgrade"/>
When a `schema` parameter is specified, and if the DB is originally at version `1`, then only functions labeled `2` and above are executed. 
This provides a way to migrate database by creating object stores, indexes or even reading/writing data between database versions. 
For details on the `transaction` parameter, looks at the [Transaction] (#trans) object returned during a transaction. 

Note that the `createObjectStore`
and the `deleteObjectStore` are available only during the upgrade operations. 
Also, `objectStores` opened during progress can have `index` operations. See the [indexes] (#index) section for more details

If the optional parameter is not specified, it simply opens the database to the latest version available.  

It returns a [Jquery Promise] ("http://api.jquery.com/category/deferred-object/") with the following 
[done] (#dbOpenDone), [progress] (#dbOpenProgress) and [fail] (#dbOpenFail) event handlers. 

### Handling Database open success <a name = "dbOpenDone"/>

``` javascript
dbOpenPromise.done(function(db, event){
	// Called when the database is successfully opened. 
	db;  //  the native IndexedDB Database object (aka result of the IDBRequest) ,
	event; // the IndexedDB Event object.  
	this; // Context inside the function is the native IDBRequest.
});
```

### When the database open is in progress <a name = "dbOpenProgress"/>
When that database is being upgraded or is blocked due to another transaction being in progress 

``` javascript
dbOpenPromise.progress(function(db, event){
	// Called when there is the database open is in progress - when it is blocked or is being upgraded 
	error; // is the error object and has more details on what the error is
	event; //  is the IndexedDB Event object
	event.type; //indicates - blocked or upgrade
	this; // Context inside the function is the native IDBRequest
});
```
When a database open operation is blocked, you can choose to close the database. 
When the database is being upgraded, you can perform all actions permitted in the versionChange transaction.

### Handling database open error <a name = "dbOpenFail"/>

``` javascript
dbOpenPromise.fail(function(error, event){
	// Called when there is an error opening the database. 
	error; //is the error object and has more details on what the error is
	event; //is the IndexedDB Event object. event.type indicates the type - 'error' or 'exception'
	this; // Context inside the function is the native IDBRequest	
});
```
Transactions  <a name = "transactionSec"/>
--------------------------
Once a database is opened, read and write transactions can be performed within a transaction.

	var transactionPromise = $.indexedDB("dbName").transaction(storeNames, mode);

`storeNames` is an array of object store names (or a single string object store name) that should be under this transaction. 

<a name = "transactionMode"/> 
`mode` is 0 or 1 indication *READ_ONLY* or *READ_WRITE*, similar to [modes] (http://www.w3.org/TR/IndexedDB/#dfn-mode) in the IndexedDB Specification.  

The returned transaction promise has the following event handlers during the lifetime of the transaction.  

### Transaction in progress <a name = "transInProgress"/>
	
``` javascript
transactionPromise.progress(function(trans){
	// Called when the transaction has started
	trans; // Use the methods on the trans object (see below) to perform operations
});
```
	
<a name = "trans"/> The transaction object passed to the callback when transaction is in progress has the following methods on it. 

``` javascript
var objectStore = trans.objectStore("objectStoreName");
```

The following 2 methods are available only when the database is being upgraded. Look at the [Open Database Schema] (#openDatabaseUpgrade) section for details. 

``` javascript
var objectStore = trans.createObjectStore("objectStoreName", {
	// Options to create object store. 
	"autoIncrement" : true,  // [detaults to true], indicating that the key for this object store should auto increment,
	"keyPath" : id // the path of key in the object, defaults to key that has to be specified separately
}); 

trans.deleteObjectStore(objectStoreName); 
```
See [object stores] (#objectStore) for methods on the `objectStore` returned by the above calls.

### Transaction complete

``` javascript
transactionPromise.done(function(event){
	// Called when transaction is completed
	event; // Indicated the transaction complete event.
});
```

### Transaction fails or is aborted

``` javascript
transactionPromise.fail(function(event){
	// Called when the transaction is aborted or fails
	event.type; // indicates the reason for failure being error, exception or abort
});
```
 
Object Stores <a name = "objectStore"/>
----------------------------------------
Once the database is opened, operations need to be performed on object stores. 
An object store can be opened inside a [transaction that is in progress] (#transInProgress) or using a shorthand on the `$.indexedDB` object like. 

``` javascript
var objectStore = $.indexedDB("database_name").objectStore("objectStoreName", /* Optional */ mode );
``` 

The `mode` parameter defaults to READ_WRITE and is similar to the `mode` parameter specified during a `transaction`. 

As a convenience method, if the `mode` is set to `true` (instead of 0 or 1), an object store is created if it does not exist. Internally, the database is closed and opened with a higher version to trigger the version transaction where the object store can be created.  

<a name = "crud"/>
The above expression internally creates a transaction for this object store. The `mode` parameter is optional and similar to the [mode parameter] (#transactionMode) in transactions. 
The CRUD methods on the object store are 

```javascript
var promise = objectStore.add(/*Javascript Object*/ value, /*Optional*/ key); // Adds data to the objectStore
var promise = objectStore.get(key); Gets the object with the key 
var promise = objectStore.put(/*Javascript Object*/ value, key); // Updates the object for the specified key 
var promise = objectStore.delete(key); // Deletes the object with the specified key
var promise = objectStore.count(); // Gets all the objects
var promise = objectStore.clear(); // Removes all data from the object store;
```

The returned promise can be used to note the success or error of the operations 

``` javascript
promise.done(function(result, event){
	result; // Result of the operation. Some operations like delete will return undefined
	event; // Success Event
});

promise.fail(function(error, event){
	error; // Type of error that has occured
	event; // Error event
	event.type; // indicates if there was an error or an exception
});
```

<a name = "cursorEach"/>
To iterate over the objects inside an object store, use

``` javascript
var iterationPromise = objectStore.each(function(item){
	// Called for each element during the iteration
	item.key, item.value; // The key and the value of current object
	item.delete(); // Deletes the current item
	item.update(newItem); // Updates the current item with newItem;
	
	return; 
	// false - do not continue iteration
	// integer 'n' - n can be 1,2,... indicating skip next n objects and continue
	// object - continue to item with object as the next key
	// default - no return, or undefined return, continue iteration
	  
}, /*Optional*/ range, /*Optional*/ direction);

iterationPromise.done(function(result, event){
	// Iteration completed
	result ; // null, indicating that there are no more objects for iteration
	event ; // Success event
})

iterationPromise.fail(function(error, event){
	error; // Error during iteration
	event; // Error event, can be exception or event
});

```
`range` limits the results and can be an array like `[lower_limit, upper_limit, can_include_lower, can_include_upper]`.
If only one element is specified in the array, it becomes an equals clause. The parameters `can_include_lower` and `can_include_upper` are optional and default to true.

In addition to the above CURD operation, `objectStore.index` methods also allow operations using indexes. See [indexes] (#index) for details. 

Indexes <a name = "index"/>
---------------------------
Once a reference to an objectStore is obtained either using `transaction.objectStore()`, `transaction.createObjectStore()` or `$.indexedDB("").objectStore()`,
the index object can be used. 

``` javascript
	var index = objectStore.index("indexName");
	index.each(function(item){
		// Iterate over objects in index
		// Similar to iterating over objects in an ObjectStore
		item; // same as iterating over objects (see above) 
	}, /*Optional*/ range, /*Optional */ direction);
	
	index.eachKey(function(item){
		// 	Iterate over the keys of the object
	});
```

While upgrading a database in the [version change transaction] (openDatabaseUpgrade), indexes can also be created or deleted on an object store. 

```javascript
	// trans is created when a database upgrade is in progress
	var objectStore = trans.objectStore("objectStoreName");
	var index = objectStore.createIndex("object.property" , /*Optional*/ {
		"unique" : false, // Uniqueness of Index, defaults to false
		"multiEntry" : false // see explanation below
	}, /* Optional */ "indexName")
	objectStore.deleteIndex("indexName"); //returns nothing
	
```
If the second argument to the `createIndex` function is a string, it is considered to be the name of the index. If no indexName is specified in `createIndex`, the property name is used as indexName

This multiEntry flag affects how the index behaves when the result of evaluating the index's key path yields an Array.
 
* If the multiEntry flag is false, then a single record whose key is an Array is added to the index. 
* If the multiEntry flag is true, then the one record is added to the index for each item in the Array. The key for each record is the value of respective item in the Array. 

Delete Database <a name = "deleteDatabase"/>
-------------------------------
A database can be deleted using 

``` javascript
var deletePromise = $.indexedDB("database_name").deleteDatabase();

deletePromise.done(function(null, event){ 
	/* Called when the delete is successful*/
	event; // The success event
});
deletePromise.fail(function(error, event){ 
	/* Called when the delete is successful*/
	error; // Reason for the error
});
deletePromise.progress(function(db, event){ 
	// Called when the deleting is blocked due to another transaction
	db; // Database that is opened
	event.type // Indicates it is blocked, etc. 
});
```

Compare Keys
---------------------
A convenience method to compare keys in a database. Can be used as `$.indexedDB("dbName").cmp(key1, key2)` and return 1,0 or -1 when key1 is greater than, equal to or less than key2 respectively.  

Links
-------
Some useful links

* [IndexedDB W3C Specification] (http://www.w3.org/TR/IndexedDB/)
* [IndexedDB API playground and examples] (http://nparashuram.com/IndexedDB)
* [My work on IndexedDB] (http://blog.nparashuram.com/search/label/indexeddb)

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics