1.LocalStorage示例
var Config = function ( name ) { //storage为空时,初始化的信息
var storage = {
'name': 'test', 'theme': 'css/light.css', 'project/renderer': 'WebGLRenderer',
'project/renderer/antialias': true,
'project/renderer/gammaInput': false,
'project/renderer/gammaOutput': false,
'project/renderer/shadows': true,
'project/vr': false, 'settings/history': false
}; //如果本地没有初始数据,则初始化localStroage[name]
if ( window.localStorage[ name ] === undefined ) { window.localStorage[ name ] = JSON.stringify( storage ); }
//载入localstorage中名为‘name’的用户数据
else { var data = JSON.parse( window.localStorage[ name ] ); for ( var key in data ) { storage[ key ] = data[ key ]; } } //
return { getKey: function ( key ) { return storage[ key ]; }, setKey: function () { // key, value, key, value ... for ( var i = 0, l = arguments.length; i < l; i += 2 ) { storage[ arguments[ i ] ] = arguments[ i + 1 ]; } window.localStorage[ name ] = JSON.stringify( storage ); console.log( '[' + /\d\d\:\d\d\:\d\d/.exec( new Date() )[ 0 ] + ']', 'Saved config to LocalStorage.' ); }, clear: function () { delete window.localStorage[ name ]; } };
}
运行示例,可在chrome的debug页面看到存储的数据:
2.IndexDB
var Storage = function () { //使用IndexDB创建一个数据库,管理客户端上的大数据,基于事物,支持游标,异步
var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB; //若该浏览器不支持IndexDB
if ( indexedDB === undefined ) { console.warn( 'Storage: IndexedDB not available.' );
return { init: function () {}, get: function () {}, set: function () {}, clear: function () {} }; } //浏览器支持IndexDB
var name = 'IndexDBTest';
var version = 1; var database; return { init: function ( callback ) { //请求——响应的模式,返回IDBOpenDBRequest
var request = indexedDB.open( name, version );
//只有当open的给定的数据库名称和版本的数据库不存在时。才会调用onupgradeneeded,onupgradeneeded是请求数据库版本变化句柄
request.onupgradeneeded = function ( event ) { var db = event.target.result; }; //捕获request对象的onsuccess事件,onsuccess:请求成功的回调函数句柄
request.onsuccess = function ( event ) {
database = event.target.result; (); };
//onerror: 请求失败的回调函数句柄
request.onerror = function ( event ) { console.error( 'IndexedDB', event ); }; }, };
运行示例之后,可在chrome的debug页面看到建立的IndexedDB数据库。
我们可以查看IndexDB详情:
var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
console.log(indexedDB);
查看IDBOpenDBRequest
var IDBOpenDBRequest = indexedDB.open( "indexDBTest", 2 );
console.log(IDBOpenDBRequest);