IndexedDB
by sonylnagale
HTML
<!DOCTYPE html>
<html>
<head></head>
<body>
<header>
<h1>IndexedDB (<span>No</span>)</h1>
</header>
<article>
<label for="whish">Enter a wish:</label>
<input type="text" id="wish" />
<button id="btnSave">Keep it</button>
<div id="result">
<h2>My wishes:</h2>
<ul id="list"></ul>
</div>
</article>
</body>
</html>
CSS
body{
font-family: "Verdana";
font-size: 9pt;
}
header{
padding: 15px;
box-shadow: 0px 1px 2px rgba(0,0,0,0.4);
background-color: rgb(27, 161, 226);
color: #fff;
}
header h1{
font-size:14pt;
}
header span{
color: red;
}
h2{
font-size: 12pt;
font-weight: bold;
}
article{
width: 80%;
margin:auto;
margin-top:20px;
}
button{
padding:10px;
background-color: #E0811B;
color: #fff;
border-radius: 4px;
}
input{
padding:10px;
}
#result{
margin-top:20px;
}
#result ul{
margin-top: 10px;
}
#result ul li{
font-style: italic;
}
#result ul li a
{
cursor: pointer;
}
JavaScript
// #region
/**
* PolyFill IDBKeyRange for a key prefix search.
*
* In IndexedDB, Primary keys are ordered, and a key range is used to selectively retrieve them without having
* to iterate the whole set and test each. We use string keys built up with various prefixes. This polyfill makes it
* possible to easily retrieve all keys with a specified prefix.
*
* @param prefix The string by which to filter the primary keys.
*/
IDBKeyRange.forPrefix = (prefix) => {
/**
* Determines the string that would sort immediately after all strings with the specified prefix and hence can be
* used as the upper bound for an IDBKeyRange to retrieve all keys with a specified prefix (where the lower bound is
* the prefix itself).
*
* @param key
*/
const successor = (key) => {
let len = key.length;
while (len > 0) {
const head = key.substring(0, len - 1);
const tail = key.charCodeAt(len - 1);
if (tail !== 0xFFFF) {
return head + String.fromCharCode(tail + 1);
}
key = head;
--len;
}
return UPPER_BOUND.STRING;
}
const upperKey = successor(prefix);
if (upperKey === undefined) {
return IDBKeyRange.lowerBound(prefix);
}
return IDBKeyRange.bound(prefix, upperKey, false, true);
};
// #endregion
// Basic sample IndexedDB usage fiddle I found
var WishesStore = function() {
//private members
var db = null,
name = null,
version = null,
trace = function(msg) {
//Traces
console.log(msg);
},
init = function(dbname, dbversion) {
//1.Initialize variables
name = dbname;
version = dbversion;
//2. Make indexedDB compatible
if (compatibility()) {
//2.1 Delete database
//deletedb("wishes");
//3.Open database
open();
}
},
compatibility = function() {
trace("window.indexedDB: " + window.indexedDB);
...