I have seen multiple JavaScript examples of using createIndex
to define an ObjectStore index directly after the ObjectStore has been created like this:
Chrome does not currently support the onupgradeneeded event. If you wanted to get a reference to an ObjectStore using the old or new W3 specs, this is one possible workaround via the onsuccess event using either the old setVersion command or via the new onupgradeneeded event:
var ixDb;
var ixDbRequest;
var ixDbVersionTansaction;
//Check to see if we have a browser that supports IndexedDB
if (window.indexedDB) {
ixDbRequest = window.indexedDB.open(dbName, dbVersion);
//For browsers like chrome that support the old set version method
ixDbRequest.onsuccess = function (e) {
ixDb = ixDbRequest.result || e.result;
if (typeof ixDb.setVersion === "function") {
//Put your version checking logic here
if (oldVersion < newVersion) {
var verRequest = ixDb.setVersion(newVersion);
verRequest.onerror = function (e) {
//handling error logic here
}
verRequest.onsuccess = function (e) {
//Get a reference to the version transaction
//from the old setVersion method.
ixDbVersionTansaction = verRequest.result;
//Create database using function provided by the user.
UserFunction();
}
}
}
};
ixDbRequest.onupgradeneeded = function (e) {
//FF uses this event to fire the transaction for upgrades.
//All browsers will eventually use this method. Per - W3C Working Draft 24 May 2012
ixDb = ixDbRequest.result || e.currentTarget.result;
//Get a reference to the version transaction via the onupgradeneeded event (e)
ixDbVersionTansaction = e.currentTarget.transaction;
//Create database using function provided by the user.
UserFunction();
};
UserFunction(){
//ObjectStore is accessed via ixDbVersionTansaction variable
// in either instance (transaction..objectStore("ObjectStoreName"))
var ObjectStore = ixDbVersionTansaction.objectStore("ObjectStoreName");
var index = ObjectStore.createIndex("ixName", "fieldName");
}