Docs

Everything You Need to Know

Box

Use

ChocolateChip-UI's Box is an interface to three different types of local data persistence: IndexedDB, WebSQL and localStorage. Which one it uses depends on the browser. Box first tries to use IndexedDB, if the browser does not support it, Box tries WebSQL, if the browser does not support that, it uses localStorage.

$.Box.set()

If your data needs are simple, you can use the default box. You do this by just setting your data. Box will put it in its default box called 'keyvaluepairs'. You can examine your boxes by opening the browser's Web inspector and examining your resources.

To put something in a box, let's look at the following example. We'll need to write an event to grab some data from some form inputs, and a mediator to handle putting those values in a box:

// Handle event to trigger model agumentation:
//============================================
$('#boxit').on('click', function() {
  var key = $('#key').val();
  var value = $('#value').val();
  if (!key || !value) return;
  boxMediator.run({key: key, value: value});
});

// Define Mediator to handle boxing model:
//========================================
var boxMediator = $.on('box-mediator', function(data) {
  if (data && data.key) {
    var key = data.key;
    var value = data.value;
    // Set a Box key/value pair:
    $.Box.set(key, value).then(function(item) {
      $('#boxList').empty();
      $.Box.each(function(value, key) {
        boxView.render({key: key, value: value}, 'append');
      });
    });
  }
});

$.Box.get()

You can get a key/value pair out of a box using $.Box.get(). Just give if the key you want to retrieve. Box will return a promise that you can use to access that data:

$.Box.get('name').then(function(value) {
  console.log('The name is: ' + value);
});

Because this is a promise, you can use catch to handle errors.

How Box Stores Values

A value can be any of the following:

  • Array
  • ArrayBuffer
  • Blob
  • Float32Array
  • Float64Array
  • Int8Array
  • Int16Array
  • Int32Array
  • Number
  • Object
  • Uint8Array
  • Uint8ClampedArray
  • Uint16Array
  • Uint32Array
  • String

Box will encode these depending on the type of storage it is using. When you extract a value, Box decodes it for you. That means that if you stored an array and you get it from the box, it is returned as an array. So you can immediately loop it:

$.Box.get('prices').then(function(value) {
  prices.forEach(function(price)) {
    console.log('The price is: ' + price);
  });
});

$.Box.each()

If you want to get all the keys out of your box, you can use the each() method. This will run a loop on the box, returning the key/value pairs. You can do it like this:

$.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);
  }
});