Reputation: 9453
I am trying to refactor some code I wrote that uses IndexedDb. Ideally what I would like to do is create a little business library that abstracts some of the ugliness of using IndexedDb. So for example I will create a toDoList object that will have some methods to Get, Add, Update, Delete, and inside those methods I will be calling IndexedDb.
Here is an example of what I have:
var MyApp = MyApp || {};
(function() {
var req = indexedDB.open("todostore", 1);
req.onerror = function(e) { console.log(e); };
req.onupgradeneeded = function (e) {
var newDB = e.target.result;
newDB.createObjectStore("todostore", { keyPath : "id", autoIncrement : true });
};
req.onsuccess = function () {
MyApp.db = req.result;
};
})();
MyApp.todolist = (function() {
return {
get : function(key, success) {
var tran = MyApp.db.transaction("todostore");
var req = tran.objectStore("todostore").get(key);
req.onsuccess = function (e) {
success(e.target.result);
};
}
};
})();
//consumer of library would ideally just do something like this:
var worked = function(e) {
//do something...
}
MyApp.todolist.get(1, worked);
The problem is MyApp.db is undefined in the get method because the onsuccess callback hasn't been triggered yet. I am still new to javascript, so wondering what options / patterns I could use. Thanks for any help!
Upvotes: 0
Views: 87
Reputation: 2558
There are probably 1000 different ways to handle this problem. But I would suggest simply including an option for failure in your "get" method and have that triggered if the database is not ready:
MyApp.todolist = (function() {
return {
get : function(key, success, failure) {
if(!MyApp.db) {
if(typeof failure === "function") {
failure("Database is not ready yet");
}
return;
}
var tran = MyApp.db.transaction("todostore");
var req = tran.objectStore("todostore").get(key);
req.onsuccess = function (e) {
success(e.target.result);
};
}
};
})();
//consumer of library would ideally just do something like this:
var worked = function(e) {
//do something...
};
var didntWork = function(e) {
//report the error, e.
};
MyApp.todolist.get(1, worked, didntWork);
You should also consider offering a callback method for your client to make use of to determine when the database is ready (or not). If nothing else, at least provide some way for them to easily check if the database is ready through a method. There are many options available to you based on how you want to present the tool to your users.
Upvotes: 2