YUI recommends YUI 3.

YUI 2 has been deprecated since 2011. This site acts as an archive for files and documentation.

YUI Library Home

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.




Additional Options:



Storage Name (Key)
Text Stored
Storage Name (Key)Text Stored
No records found.

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.

1function initialize() { 
2   // evaluate and create the Storage instance 
3   var engineBtn = engineRadio.get("checkedButton"); 
4   var engineType = engineBtn.get("value"); 
5   var useSession = sessionCheckbox.checked; 
6   var location; 
7 
8   location = YAHOO.util.StorageManager[useSession ? 'LOCATION_SESSION' : 'LOCATION_LOCAL']; 
9   storage = YAHOO.util.StorageManager.get(engineType, location, {force: false}); 
10 
11   storage.unsubscribe(storage.CE_CHANGE, onChange); 
12   storage.subscribe(storage.CE_CHANGE, onChange); 
13    
14   if (storage.isReady || (storage._swf && YAHOO.util.StorageManager.LOCATION_SESSION === location)) { 
15       load(); 
16   } else { 
17       saveButton.set("disabled"true);  
18       purgeButton.set("disabled"true);   
19       removeButton.set("disabled"true);  
20        
21       engineRadio.set("disabled"true); 
22    
23       storage.subscribe(storage.CE_READY, onContentReady); 
24   } 
view plain | print | ?

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.

1function onContentReady(event) { 
2    saveButton.set("disabled"false);  
3    purgeButton.set("disabled"false);   
4    removeButton.set("disabled"false); 
5     
6    engineRadio.set('disabled'false); 
7    engineRadio._buttons[0].set("disabled", ! YAHOO.util.StorageEngineHTML5.isAvailable());  
8    engineRadio._buttons[1].set("disabled", ! YAHOO.util.StorageEngineGears.isAvailable());  
9    engineRadio._buttons[2].set("disabled", ! YAHOO.util.StorageEngineSWF.isAvailable()); 
10     
11    storage.unsubscribe(storage.CE_READY, onContentReady); 
12 
13    load(); 
14
15 
16function load() { 
17    var len = storage.length, 
18        arr = []; 
19 
20    // clear the existing datatable 
21    if (datatable) 
22    { 
23        datatable.deleteRows(0, datatable.getRecordSet().getLength()); 
24    } 
25         
26    for (var i = 0, key, newobj; i < len; i++) 
27    { 
28        key = storage.key(i); 
29        newobj = { name:key, value: storage.getItem(key) }; 
30        arr.push(newobj) 
31        if (datatable) {datatable.addRow(newobj);} 
32    } 
33     
34    // only initialize the datatable once 
35    if (! datatable) 
36    { 
37        var datasource = new YAHOO.util.LocalDataSource(arr);  
38 
39        datasource.responseSchema = {fields : ["name""value"]}; 
40     
41        var configs =  
42        {    
43            scrollable: true 
44        } 
45         
46        var columns =  
47        [ 
48            {key:"name", label:"Storage Name (Key)"}, 
49            {key:"value", label:"Text Stored"
50        ]; 
51             
52        datatable = new Yahoo.widget.DataTable("datatableContainer", columns, datasource, configs); 
53    } 
54
view plain | print | ?

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

1function save() 
2
3    storage.setItem(  YAHOO.util.Dom.get('nameField').value, YAHOO.util.Dom.get('valueField').value); 
4
view plain | print | ?

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.

1function remove() 
2
3    var key = YAHOO.util.Dom.get('nameField').value; 
4    storage.removeItem(key); 
5
6 
7function removeItemAt() 
8
9    var index = parseInt(YAHOO.util.Dom.get('indexField').value), 
10        key = storage.key(i); 
11    storage.getItem(key); 
12
13 
14function purge() 
15
16    storage.clear();     
17
view plain | print | ?

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.

1function onChange(event) { 
2    //added 
3    if (event.type === YAHOO.util.StorageEvent.TYPE_ADD_ITEM || event.type === YAHOO.util.StorageEvent.TYPE_UPDATE_ITEM) 
4    { 
5        var newobj = {name: event.key, value: event.newValue}; 
6 
7        var len = datatable.getRecordSet().getLength(); 
8     
9        //loop through current records and see if this has been added before 
10        for (var i = 0; i < len; i++ ) 
11        { 
12            var rec = datatable.getRecord(i); 
13            var data = rec.getData(); 
14             
15            //if it's been added already, update it 
16            if (data.name == event.key) 
17            { 
18                datatable.updateRow(i, newobj); 
19                return
20            } 
21        } 
22 
23        //if it's not been added, add it 
24        datatable.addRow(newobj); 
25    } 
26 
27    //removed 
28    else if (event.type === YAHOO.util.StorageEvent.TYPE_REMOVE_ITEM) 
29    { 
30 
31        var len = datatable.getRecordSet().getLength(); 
32     
33        //loop through current records and see if this has been added before 
34        for (var i = 0; i < len; i++ ) 
35        { 
36            var rec = datatable.getRecord(i); 
37            var data = rec.getData(); 
38             
39            //if it's been added already, update it 
40            if (data.name == event.key) 
41            { 
42                datatable.deleteRow(i); 
43                return
44            } 
45        } 
46    }        
47
view plain | print | ?

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: Logging and debugging is currently turned off for this example.

Reload with logging
and debugging enabled.

More Storage Utility Resources:

Copyright © 2011 Yahoo! Inc. All rights reserved.

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