Skip to content

Instantly share code, notes, and snippets.

@aleksb86
Created March 11, 2019 21:16
Show Gist options
  • Save aleksb86/aa87adf9d7554fba69f2e5ae14f57fdb to your computer and use it in GitHub Desktop.
Save aleksb86/aa87adf9d7554fba69f2e5ae14f57fdb to your computer and use it in GitHub Desktop.
IndexedDb async example
var indexDB = {};
indexDB.db = null;
indexDB.logger = function(err){ console.log(err); };
indexDB.dbUpgradeneeded = function(storeNames, e) {
storeNames.forEach(function(store) {
e.currentTarget.result.createObjectStore(store, { keyPath: "id"});
});
this.db = e.target.result;
};
indexDB.performDbOpen = function(e){
this.db = e.target.result;
var afterPerformer = this.afterDbOpenPerformer;
while(afterPerformer){
afterPerformer.perform();
afterPerformer = afterPerformer.next;
}
};
indexDB.to_pending = function(f){
lastPerformer = this.afterDbOpenPerformer;
while(lastPerformer.next){ lastPerformer = lastPerformer.next }
lastPerformer.next = { next: null, perform: f }
// function(orig, pending){ orig(); pending(); }.bind(this, this.afterDbOpen.bind(this), f);
};
indexDB.afterDbOpenPerformer = { perform: function(){}, next: null };
indexDB.connect = (function(storeNames){
/*index DB*/
if (!window.webkitIndexedDB) {
console.warn('IndexedDB not supported');
return;
}
var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
var connect = indexedDB.open('TizenUSS',1);
connect.onerror = this.logger;
connect.onsuccess = this.performDbOpen.bind(this);
connect.onupgradeneeded = this.dbUpgradeneeded.bind(this, storeNames);
return connect;
}).call(indexDB, ["listTraining","listOptions"]);
/*вставка или обновление в БД*/
indexDB.insert = function(value,storeName,onsuccess,onerror){
if (!this.db){this.to_pending(this.insert.bind(this, value, storeName, onsuccess, onerror));return;}
var request = this.db.transaction([storeName], "readwrite").objectStore(storeName).put(value);
request.onerror = (onerror || this.logger).bind(null, request);
request.onsuccess = (onsuccess || function(){}).bind(null, request);
};
/*получение по ключу*/
indexDB.get = function(storeName,f,value,onsuccess){
if (!this.db){this.to_pending(this.get.bind(this, storeName, f, value, onsuccess));return;}
this.db.transaction([storeName], "readonly").objectStore(storeName).get(value).onsuccess = function(event) {
f(event.target.result);
};
};
/*получение по ключу*/
indexDB.getAll = function(storeName, onsuccess, onerror){
if (!this.db){this.to_pending(this.getAll.bind(this, storeName, onsuccess, onerror));return;}
// this.to_pending(this.getAll.bind(this, storeName, f, onsuccess))
var request = this.db.transaction([storeName], "readonly").objectStore(storeName).getAll();
request.onerror = (onerror || this.logger).bind(null, request);
request.onsuccess = (onsuccess || function(){}).bind(null, request);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment