Skip to content

Instantly share code, notes, and snippets.

@idrakimuhamad
Created December 20, 2015 15:37
Show Gist options
  • Save idrakimuhamad/8af988c66a13ff034b21 to your computer and use it in GitHub Desktop.
Save idrakimuhamad/8af988c66a13ff034b21 to your computer and use it in GitHub Desktop.
IndexDB sample
var indexDBSupport = window.indexedDB ? true : false, bookingDB;
if (indexDBSupport) {
// open the db
var open = indexedDB.open('weirdstuff',1);
// fired when the user hit the site first time
open.onupgradeneeded = function(e) {
console.log('Upgrading');
var upgradeDb = e.target.result;
// if object store not yet exists, lets create one
if (!upgradeDb.objectStoreNames.contains('Bookings')) {
upgradeDb.createObjectStore('Bookings', { autoIncrement: true });
}
};
open.onsuccess = function(e) {
console.log('DB opened');
db = e.target.result;
// lets add something
// the name of the object store and the txn operation
var txn = db.transaction(['Bookings'], 'readwrite'),
store = txn.objectStore('Bookings'),
booking = {
name: 'Brian',
email: '[email protected]',
created: new Date()
},
request = store.add(booking); // add it
// if any error during adding the data
request.onerror = function(e) {
console.error('Error in adding the data: ', e.target.error.name);
};
request.onsuccess = function(e) {
console.log('Data added');
};
};
open.onerror = function(e) {
console.log('Error in opening DB');
console.dir(e);
};
var getTxn = db.transaction(['Bookings'], 'readonly'),
getObject= getTxn.objectStore('Bookings'),
getData = getObject.get(1); // the value eg key
getData.onsuccess = function(e) {
console.log(e.target.result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment