Docs
Everything You Need to Know
Box
API
Handling Results
ChocolateChip-UI Box offers two ways of using its API, through functions or promises. The functions work like Node functions. You'll be doing everythin inside a callback:
$.Box.set('key', obj, function(err, ret) { alert(ret.value); });
You could write code that returns the result like a normal array, however, you would pay a price in performance, since the data request will be blocking:
var stuff = JSON.parse($.Box.get('myStuff')); console.log(stuff);
Contrast that with this, which is non-blocking:
$.Box.get('key', function(err, stuff) { alert(stuff); });
You can handle errors inside a callback. The error will be the the first argument, just like Node:
$.Box.get('key', function(err, stuff) { if (err) { console.error('Houston, we have a problem!'); } else { alert(stuff); } });
When using promises, remember that promises are async. You'll need to do whatever you are trying to accomplish inside of the promise. The following are the same examples from above with promises:
$.Box.get('key') .then(function(stuff) { alert(stuff); });
You can handle errors as you normally would in a promise:
$.Box.set('key', 'value') .then(function(value) { alert(value + ' was set!'); // Handle error: }, function(error) { console.error(error); }); // Or use catch: $.Box.set('key', 'value') .then(function(value) { alert(value + ' was set!'); }) // Handle error: .catch(function(error) { console.error(error); });
set
set(key, value, successCallback)
Saves data to an offline store. You can store the following types of JavaScript objects:
- Array
- ArrayBuffer
- Blob
- Float32Array
- Float64Array
- Int8Array
- Int16Array
- Int32Array
- Number
- Object
- Uint8Array
- Uint8ClampedArray
- Uint16Array
- Uint32Array
- String
A key name has the same restrictions as any object property: it must be alpha-numeric. The underscore character, "_", is permitted, other word delimiters are not: ". , ; -", etc.
$.Box.set('somekey', 'some value', function(err, value) { // Output the value: console.log(value); }); // You can store non-strings: $.Box.set('my array', [1, 2, 'three'], function(err, value) { // This will output `1`: console.log(value[0]); }); // Store binary data: request = new XMLHttpRequest(); request.open('GET', '/myPhoto.jpg', true); request.responseType = 'arraybuffer'; request.addEventListener('readystatechange', function() { // Request complete: if (request.readyState === 4) { $.Box.set('myPhoto', request.response); } });
get
get(key, successCallback)
Gets an item from the storage library and supplies the result to a callback. If the key does not exist, get()
will return null.
get()
. This is due to a limitation in localStorage, and for compatibility reasons $.Box cannot store the value undefined.$.Box.get('somekey', function(err, value) { // Output the value: console.log(value); }); // Same code using Promises: $.Box.get('somekey') .then(function(value) { console.log(value); });
remove
remove(key, successCallback)
Removes the value of a key from the offline store.
// Execute callback after the key has been removed: $.Box.remove('somekey', function(err) { console.log('Key is cleared!'); });
clear
clear(successCallback)
Removes every key from the database, returning it to a blank slate.
// Execute callback after the database has been deleted: $.Box.clear(function(err) { console.log('Database went bye-bye.'); });
size
size(successCallback)
Gets the number of keys in the offline store (i.e. its “size”).
// Output the number of keys in the database: $.Box.size(function(err, numberOfKeys) { console.log(numberOfKeys); });
key
key(keyIndex, successCallback)
Get the name of a key based on its ID.
// Output the key name: $.Box.key(2, function(err, keyName) { console.log(keyName); });
keys
keys(successCallback)
Get the list of all keys in the datastore.
// An array of all the key names: $.Box.keys(function(err, keys) { console.log(keys); });
each
each(successCallback)
Iterate over all value/key pairs in datastore.
successCallback
is called once for each pair, with the following arguments:
- value
- key
- idx - one-based number
// This callback will be executed for every item in the database: $.Box.each(function(value, key, idx) { console.log([key, value]); }, function(err) { if (!err) { console.log('each has completed.'); // Handle any error: } else { console.log(err); } }); // The same code using Promises: $.Box.each(function(value, key, idx) { console.log([key, value]); }) .then(function() { console.log('Iteration has completed.'); }) .catch(function(err) { console.log(err); }); // Exit the iteration: $.Box.each(function(value, key, idx) { if (idx < 5) { console.log([key, value]); } else { return [key, value]; } }, function(err, result) { if (!err) { console.log('Iteration has completed.'); console.log('The last iterated pair was:'); console.log(result); } }); // The same code using Promises: $.Box.each(function(value, key, idx) { if (idx < 5) { console.log([key, value]); } else { return [key, value]; } }) .then(function(result) { console.log('Iteration has completed.'); console.log('The last iterated pair was:'); console.log(result); });
each
supports early exit by returning an undefined value inside the eachCallback. The resulting value will be passed to successCallback with each iteration.createInstance
createInstance(options)
You can create multiple instances of ChocolateChip-UI Box. createInstance
accepts all the options that config does (see below). Each instance can have its own name to identify it.
// Setup: var moviesBox = $.Box.createInstance({ name: 'MoviesDB' }); recipesBox.set('movie1', {...}); var recipiesBox = $.Box.createInstance({ name: 'RecipesDB' }); recipesBox.set('recipe1, {...}'); // Get a movie from its box: moviesBox.get('movie1') .then(function(movie) { console.log(movie.name); });
Settings
These methods allow driver selection and database configuration. They should generally be called before the first data API call to $.Box (i.e. before you call get()
, size()
, etc.)
setDriver
setDriver(driverName)
setDriver([driverName, nextDriverName])
Force usage of a particular driver or drivers, if available.
By default, $.Box selects drivers for the datastore in this order:
- IndexedDB
- WebSQL
- localStorage
If you want to force the usage of a particular driver, you can use setDriver()
with one or more of the following parameters:
- $.Box.INDEXEDDB
- $.Box.WEBSQL
- $.Box.LOCALSTORAGE
// Force Box to use localStorage: $.Box.setDriver($.Box.LOCALSTORAGE); // Tell Box what your order preference is: $.Box.setDriver([$.Box.WEBSQL, $.Box .INDEXEDDB, $.Box.LOCALSTORAGE]);
config
config(options)
Set and persist $.Box options. This must be called before any other calls to $.Box are made, but can be called after $.Box is loaded. If you set any config values with this method, they will persist after driver changes, so you can call config()
then setDriver()
. The following config values can be set:
driver
The preferred driver(s) to use. Same format as what is passed to setDriver()
, above.
Default: [$.Box.INDEXEDDB, $.Box.WEBSQL, $.Box.LOCALSTORAGE]
name
The name of the database. This may appear during storage limit prompts. Since the user may see this, it is best to use the name of your app. In localStorage, this is used as a key prefix for all keys stored in localStorage.
Default: 'ChuiBox'
size
The size of the database in bytes. Used by WebSQL and localStorage.
Default: 4980736
boxName
The name of the datastore. In IndexedDB this is the dataStore, in WebSQL this is the name of the key/value table in the database. This must be alphanumeric, with underscores. Any non-alphanumeric characters will be converted to underscores.
Default: 'keyvaluepairs'version
The version of your database.
Default: 1.0
description
A description of the database. This is only as a reminder for you, the developer. By default this value is empty.
Default: ''
// This will rename the database from "ChuiBox" // to "Bongo Babies App". $.Box.config({ name: 'Bongo Babies App' }); // This will replace whatever the current // storage driver is with localStorage. // This is the same as using `setDriver()`. $.Box.config({ driver: $.Box.LOCALSTORAGE, name: 'localStorage-always-works' }); // Use a different driver order. $.Box.config({ driver: [$.Box.WEBSQL, $.Box.INDEXEDDB, $.Box.LOCALSTORAGE], name: 'WebSQL-First' });