2012-08-25 15 views
5

Jestem świadomy, że IDBObjectStore.getAll is not part of the IndexedDB standard i że . Ale jest zaimplementowany w FireFox i sprawia, że ​​twój kod jest ładniejszy, jeśli musisz odzyskać wiele obiektów z bazy danych.IndexedDB getAll w przeglądarkach innych niż Firefox

Czy można utworzyć coś w rodzaju polyfill lub coś, co pozwoli getAll na pracę w innych przeglądarkach obsługujących IndexedDB? Rzeczywista funkcjonalność getAll jest prosta, ale nie wiem jak sobie poradzić z asynchroniczną naturą IndexedDB w kontekście replikacji jej dokładnej składni w przeglądarkach innych niż Firefox.

Odpowiedz

10

Zrobiłem a GitHub repo for a shim to support getAll in other browsers, który wydaje się działać dobrze w Chrome. Kod jest powtarzany poniżej dla potomności:

(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

Witam, mówiąc z 4 lat w przyszłości; Potrzebowałem twojego kodu, żeby działał w "Pozwól ci najpierw zgadnąć ..." yessss, Internet Explorer (klaszcz klaskać) – sergio0983

+1

LOL IE/Edge są wciąż tak daleko w tyle. – user1133275

Powiązane problemy