IndexedDB - multiple items for an id -
i'm trying build indexeddb application uses following (one-to-many key value pair, i.e. each id has multiple images) data structure:
var images = [{"id": "1", "img":["img1","img2","img3"]}, {"id": "1", "img":["img4","img5","img6"]}]
my question how put , using structure. examples out there either iterate through keys or have single value associated each key can get. can open cursor on get('id') method , iterate through "img" items id? here's have tried:
1) getting specific key(one-to-one mapping):
var dbget = function(id, cbget){ var transaction = db.transaction(["images"],"readonly"); var objectstore = transaction.objectstore("images"); var request = objectstore.get(id); request.onerror = function(event) {}; request.onsuccess = function(e) { if(typeof(e.target.result) != "undefined"){ cbget(null,null,e.target.result); } }; };
2) getting keys:
var dbgetall = function(id){ var transaction = db.transaction(["images"],"readonly"); var objectstore = transaction.objectstore("images"); objectstore.opencursor().onsuccess = function(event) { var cursor = event.target.result; if (cursor) { //do cursor.continue(); } }; }
3) how 'all' specific key (one-to-many mapping)?
found answer myself, posting here others might struggling this:
1) existing array of values given key:
function getexisting(id, object){ var existingimgarr = new array(); var transaction = db.transaction(["images"],"readonly"); var objectstore = transaction.objectstore("images"); var request = objectstore.get(id); request.onerror = function(event) { }; request.onsuccess = function(e) { if(typeof(e.target.result) != "undefined"){ existingimgarr = (e.target.result.img); } dbsavewithexisting(id, object,existingimgarr); };
2) second, on success callback of above, call function append existing array of vals:
function appendtoexisting(id, object, imgarr){ var transaction = db.transaction(["images"], "readwrite"); transaction.oncomplete = function(event) {}; transaction.onerror = function(event) {}; var objectstore = transaction.objectstore("images"); imgarr.push(object.value); var data = {"id": id, "img": imgarr }; var request = objectstore.put(data); request.onsuccess = function(event) {}; }
Comments
Post a Comment