2012-08-25 18 views
5

私はIDBObjectStore.getAll is not part of the IndexedDB standardとそのを認識しています。しかし、これはFireFoxに実装されており、データベースからたくさんのオブジェクトを取得する必要がある場合は、コードがきれいになります。Firefox以外のブラウザでIndexedDB getAll

getAllが、IndexedDBをサポートする他のブラウザでも動作するようにするには、ある種のポリフィルなどを作成することはできますか? getAllの実際の機能は単純ですが、Firefox以外のブラウザでも正確な構文を複製するというコンテキストで、IndexedDBの非同期性をどのように扱うかはわかりません。

答えて

10

a GitHub repo for a shim to support getAll in other browsersを作成しました。これはChromeで十分に機能するようです。コードは後で説明するために以下のように繰り返します:

(function() { 
    "use strict"; 

    var Event, getAll, IDBIndex, IDBObjectStore, IDBRequest; 

    IDBObjectStore = window.IDBObjectStore || window.webkitIDBObjectStore || window.mozIDBObjectStore || window.msIDBObjectStore; 
    IDBIndex = window.IDBIndex || window.webkitIDBIndex || window.mozIDBIndex || window.msIDBIndex; 

    if (typeof IDBObjectStore.prototype.getAll !== "undefined" && typeof IDBIndex.prototype.getAll !== "undefined") { 
     return; 
    } 

    // https://github.com/axemclion/IndexedDBShim/blob/gh-pages/src/IDBRequest.js 
    IDBRequest = function() { 
     this.onsuccess = null; 
     this.readyState = "pending"; 
    }; 
    // https://github.com/axemclion/IndexedDBShim/blob/gh-pages/src/Event.js 
    Event = function (type, debug) { 
     return { 
      "type": type, 
      debug: debug, 
      bubbles: false, 
      cancelable: false, 
      eventPhase: 0, 
      timeStamp: new Date() 
     }; 
    }; 

    getAll = function (key) { 
     var request, result; 

     key = typeof key !== "undefined" ? key : null; 

     request = new IDBRequest(); 
     result = []; 

     // this is either an IDBObjectStore or an IDBIndex, depending on the context. 
     this.openCursor(key).onsuccess = function (event) { 
      var cursor, e, target; 

      cursor = event.target.result; 
      if (cursor) { 
       result.push(cursor.value); 
       cursor.continue(); 
      } else { 
       if (typeof request.onsuccess === "function") { 
        e = new Event("success"); 
        e.target = { 
         readyState: "done", 
         result: result 
        }; 
        request.onsuccess(e); 
       } 
      } 
     }; 

     return request; 
    }; 

    if (typeof IDBObjectStore.prototype.getAll === "undefined") { 
     IDBObjectStore.prototype.getAll = getAll; 
    } 
    if (typeof IDBIndex.prototype.getAll === "undefined") { 
     IDBIndex.prototype.getAll = getAll; 
    } 
}()); 
+1

こんにちは、そこから4年後の話です。 "私はあなたが最初に推測できるようにするためにあなたのコードが必要でした" yessss、Internet Explorer(clap clap) – sergio0983

+1

lol IE/Edgeはまだまだ遅れています。 – user1133275

関連する問題