YUI Library Home

Site Search (YDN & YUIBlog):

# YUI Library Examples: Storage Utility: Advanced Storage Example

# Storage Utility: Advanced Storage Example

This example shows how to get, set, and remove items from storage using the YUI Storage Utility and how to display the current storage contents in a DataTable.

View example in new window.

Storage name:
Text to store:
Additional Options:

## Advanced Storage Example

This example consists of two text fields, a few Buttons and a DataTable. The Buttons allow you to save data, set properties on your `YAHOO.util.Storage` instance, or clear all items from storage.

Once the page is drawn, initialize is called to instantiate a `YAHOO.util.Storage` instance and set up some listeners. We also disable all of the Buttons until the `YAHOO.util.Storage` instance is ready.

function initialize() { // evaluate and create the Storage instance var engineBtn = engineRadio.get("checkedButton"); var engineType = engineBtn.get("value"); var useSession = sessionCheckbox.get("checked"); var location; location = YAHOO.util.StorageManager[useSession ? 'LOCATION_SESSION' : 'LOCATION_LOCAL']; storage = YAHOO.util.StorageManager.get(engineType, location, {force: false}); storage.unsubscribe(storage.CE_CHANGE, onChange); storage.subscribe(storage.CE_CHANGE, onChange); if (storage.isReady || (storage._swf && YAHOO.util.StorageManager.LOCATION_SESSION === location)) { load(); } else { saveButton.set("disabled", true); purgeButton.set("disabled", true); removeButton.set("disabled", true); engineRadio.set("disabled", true); storage.subscribe(storage.CE_READY, onContentReady); } }

When `storage` is ready, it will dispatch a `storage.CE_READY` event. We can then enable the Buttons and initialize a DataTable with any previously stored values. Because items are stored as key/value pairs, we need to loop through them to turn them into name-value pairs suitable for use with the DataTable. The `load` function is called on page initialization and each time you switch engine options, creating or updating `datatable` as necessary.

function onContentReady(event) { saveButton.set("disabled", false); purgeButton.set("disabled", false); removeButton.set("disabled", false); engineRadio.set('disabled', false); engineRadio._buttons[0].set("disabled", ! YAHOO.util.StorageEngineHTML5.isAvailable()); engineRadio._buttons[1].set("disabled", ! YAHOO.util.StorageEngineGears.isAvailable()); engineRadio._buttons[2].set("disabled", ! YAHOO.util.StorageEngineSWF.isAvailable()); sessionCheckbox.set("disabled", false); storage.unsubscribe(storage.CE_READY, onContentReady); load(); } function load() { var len = storage.length, arr = []; // clear the existing datatable if (datatable) { datatable.deleteRows(0, datatable.getRecordSet().getLength()); } for (var i = 0, key, newobj; i < len; i++) { key = storage.key(i); newobj = { name:key, value: storage.getItem(key) }; arr.push(newobj) if (datatable) {datatable.addRow(newobj);} } // only initialize the datatable once if (! datatable) { var datasource = new Yahoo.util.LocalDataSource(arr); datasource.responseSchema = {fields : ["name", "value"]}; var configs = { scrollable: true } var columns = [ {key:"name", label:"Storage Name (Key)"}, {key:"value", label:"Text Stored"} ]; datatable = new Yahoo.widget.DataTable("datatableContainer", columns, datasource, configs); } }

The save Button is set up to take the values from the text fields and store them, using the setItem method of `storage`.

function save() { storage.setItem( YAHOO.util.Dom.get('nameField').value, YAHOO.util.Dom.get('valueField').value); }

Similarly, a couple of other Buttons are set up to remove items from `storage`, either by name or index, or by clearing the entire local store.

function remove() { var key = YAHOO.util.Dom.get('nameField').value; storage.removeItem(key); } function removeItemAt() { var index = parseInt(YAHOO.util.Dom.get('indexField').value), key = storage.key(i); storage.getItem(key); } function purge() { storage.clear(); }

We've already set up a listener for a `storage.CE_CHANGE` event, which is dispatched whenever an item is successfully added, updated, or deleted. That calls this function, which loops through the DataTable. Using the info property of the event, we can determine what type of change occurred, and either add rows to it, delete rows from it, or update its current values.

function onChange(event) { //added if (event.type === YAHOO.util.StorageEvent.TYPE_ADD_ITEM || event.type === YAHOO.util.StorageEvent.TYPE_UPDATE_ITEM) { var newobj = {name: event.key, value: event.newValue}; var len = datatable.getRecordSet().getLength(); //loop through current records and see if this has been added before for (var i = 0; i < len; i++ ) { var rec = datatable.getRecord(i); var data = rec.getData(); //if it's been added already, update it if (data.name == event.key) { datatable.updateRow(i, newobj); return; } } //if it's not been added, add it datatable.addRow(newobj); } //removed else if (event.type === YAHOO.util.StorageEvent.TYPE_REMOVE_ITEM) { var len = datatable.getRecordSet().getLength(); //loop through current records and see if this has been added before for (var i = 0; i < len; i++ ) { var rec = datatable.getRecord(i); var data = rec.getData(); //if it's been added already, update it if (data.name == event.key) { datatable.deleteRow(i); return; } } } }

## Configuration for This Example

You can load the necessary JavaScript and CSS for this example from Yahoo's servers. Click here to load the YUI Dependency Configurator with all of this example's dependencies preconfigured.

### YUI Logger Output:

Note: You are viewing this example in debug mode with logging enabled. This can significantly slow performance.

Reload with logging
and debugging disabled.

### Storage Utility Examples:

- Simple Storage Example — Saving In-Progress Text Entry
- Advanced Storage Example

### More Storage Utility Resources:

- User's Guide (external)
- API Documentation
- Cheat Sheet PDF (external)

Copyright © 2009 Yahoo! Inc. All rights reserved.

Privacy Policy - Terms of Service - Copyright Policy - Job Openings