0

As a basic example, I click a button then a record is entered into the indexeddb objectstore. I now want to knockout observable updated with the new record.

The code below works. However, I am wondering if this is the right way to do it. The "getAll" function is a IndexedDB-getAll-shim that I found.

self.addPersonRecord = function(){
    // item being added
    data = {name: "Some User", email: "aa2314123@something.com" };
    var obj = db.transaction(["people"], "readwrite").objectStore("people");
    var req = obj.add(data);

    // result of save
    req.onsuccess = function(event) {

        // get all items from db
        obj.getAll().onsuccess = function (ev) {
            // update observable
            self.chosenPageData({people: ev.target.result});
        };
    };

};
Dave Ferguson
  • 743
  • 3
  • 10
  • 2
    It's not clear what your question is - you can push into an observableArray - is that what you are asking? – PW Kad Jan 30 '14 at 03:29
  • 1
    The only thing I'd be worried about with that code is that `onsuccess` doesn't guarantee the data is written until the transaction is complete, so you might want to do the `getAll` in a new transaction to avoid a race condition. See http://stackoverflow.com/questions/15151242/running-code-only-after-an-object-is-updated-in-indexeddb-particularly-in-chrom – dumbmatter Jan 30 '14 at 05:02

1 Answers1

0

Your approach seems fine. A couple suggested improvements:

  • There should be no reason to getAll() following an add. An object store addition should return the primary key, which you can then use to lookup that object.

  • I'd use the complete event rather than a success event myself as I've found sometimes the data isn't actually available on event.target.result until that time.

buley
  • 28,032
  • 17
  • 85
  • 106