IDB Canonical

by taylorbuley

JavaScript

window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || { READ_WRITE: "readwrite" };

var EditorsIDBFiddle = function( ready ) {
    var that = this;
    this.config = {
        database: 'mydatabase14'
        , store: 'mystore3'
        , keypath: 'id'
    };
    this.open = window.indexedDB.open( this.config.database );
    this.onerror = function( event ) {
        throw new Error();
    };
    this.onupgradeneeded = function( event ) {
        that.database = event.target.result;
        var args = [ that.config.store ], request;
        if ( that.config.keypath ) {
            args.push( { keyPath: that.config.keypath } );
        }
        that.database.createObjectStore.apply( that.database, args );
    };
    this.onsuccess =function( event ) {
        that.database = event.target.result;
        if ( 'function' === typeof ready ) {
              ready.apply( that, [] );
        } 
    }
    this.open.addEventListener( 'error', this.onerror );
    this.open.addEventListener( 'success', this.onsuccess );
    this.open.addEventListener( 'upgradeneeded', this.onupgradeneeded );
};

EditorsIDBFiddle.prototype.create = function( object, success, error ) {
  var transaction = this.database.transaction( [ this.config.store ], "readwrite" )
    , store = transaction.objectStore( this.config.store )
    , onsuccess = function( event ) {
          if ( 'function' === typeof success ) {
              success.apply( that, [ result.value, result.key ] );
          }      
    }
    , onerror = function( event ) {
          if ( 'function' === typeof error ) {
              error.apply( that, [ result.value, result.key ] );
          }      
    }
    , request = store.add( object );
    request.addEventListener( 'error', onerror );
    request.addEventListener( 'success', onsuccess );
};

EditorsIDBFiddle.prototype.read = function( success, error, complete ) {
    var transaction = this.database.transaction( [ this.config.store ])
      ,...