1 /** 2 * Module for simplifying Indexed DB access 3 */ 4 (function() { 5 "use strict"; 6 7 var db = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB, 8 indexedDB = {}; 9 10 //Well, some browsers don't support it yet 11 if(typeof db === "undefined") 12 { 13 return; 14 } 15 16 /** 17 * Module for simplifying Indexed DB access 18 * 19 * @namespace 20 * @name indexedDB 21 * @memberOf $_ 22 */ 23 indexedDB = { 24 current_db: null, 25 /** 26 * Connects to an indexedDB database 27 * 28 * @memberOf $_.indexedDB 29 * @name connect 30 * @function 31 * @param string dbname 32 * @param [int] version 33 * @param [function] onupgradeneeded 34 */ 35 connect: function(dbname, version, onupgradeneeded) 36 { 37 var request = {}; 38 39 version = version || 1; 40 41 // Ask for permission to use db 42 request = db.open(dbname, version); 43 44 // Assign onupgradeneeded callback 45 if(typeof onupgradeneeded !== "undefined") 46 { 47 request.onupgradeneeded = onupgradeneeded; 48 } 49 50 /** 51 * @private 52 */ 53 request.onerror = function(event) 54 { 55 console.log("IndexedDB disallowed."); 56 }; 57 58 /** 59 * @private 60 */ 61 request.onsuccess = function(event) 62 { 63 // Connect to the specified db 64 indexedDB.current_db = request.result; 65 }; 66 }, 67 /** 68 * Helper function to create a new object store 69 * 70 * @memberOf $_.indexedDB 71 * @name create_store 72 * @function 73 * @param string name 74 * @param [string] key 75 * @param [bool] generator 76 * @return IDBDataStore object 77 */ 78 create_store: function(name, key, generator) 79 { 80 var params = {}; 81 82 if(typeof key !== "undefined") 83 { 84 params.keyPath = key; 85 } 86 87 if(typeof generator !== "undefined") 88 { 89 // Cast to a boolean value 90 params.autoIncrement = !! generator; 91 } 92 93 return db.createObjectStore(name, params); 94 }, 95 /** 96 * Delete an object store 97 * 98 * @memberOf $_.indexedDB 99 * @name delete_store 100 * @function 101 * @param string name 102 */ 103 delete_store: function(name) 104 { 105 var request = db.deleteObjectStore(); 106 107 // Pass the error up 108 request.onerror = db.onerror; 109 } 110 111 }; 112 113 $_.ext('indexedDB', indexedDB); 114 115 }());