Jump to Table of Contents

Cache

The Cache Utility provides a basic caching mechanism for storing key/value pairs in local JavaScript memory. As a subclass of Plugin, it is designed to seamlessly integrate with other components (such as DataSource).

Upgrade Notes

Cache as a plugin has changed
Implementers upgrading from version 3.1.1 or earlier who are using Cache as a plugin now need to point to Y.Plugin.Cache instead of Y.Cache.

Getting Started

To include the source files for Cache and its dependencies, first load the YUI seed file if you haven't already loaded it.

<script src="http://yui.yahooapis.com/3.8.0/build/yui/yui-min.js"></script>

Next, create a new YUI instance for your application and populate it with the modules you need by specifying them as arguments to the YUI().use() method. YUI will automatically load any dependencies required by the modules you specify.

<script>
// Create a new YUI instance and populate it with the required modules.
YUI().use('cache', function (Y) {
    // Cache is available and ready for use. Add implementation
    // code here.
});
</script>

For more information on creating YUI instances and on the use() method, see the documentation for the YUI Global Object.

Using the Cache

This section describes how to use the Cache in further detail.

Basic caching

Basic caching allows you to store frequently used data in local JavaScript memory. In cases where data is retrieved over the wire from a server, you can store the response in a local cache and eliminate future trips to the server for better performance and reduced server load.

Use the following Attributes to configure your Cache instance:

Attribute Default Description
max 0 The maximum number of entries the cache can hold. The cache is disabled by default! Set this value to a number greater than zero to turn on caching.
size n/a Read-only. Returns the number of entries currently stored in the cache.
entries n/a Read-only. Returns an array of the entries currently stored in the cache.
expires 0 By default, expiration is disabled. To enable expiration of data, set this value to the Date when the data should expire, or the relative number of milliseconds from collection that the data should expire.
uniqueKeys false When calling add() with an entry, checks to see if the key is already stored in the cache. Enforcing unique keys requires iterating through all stored entries, so setting this attribute to false is more performant. Note: If expiration is enabled, you should probably set uniqueKeys to false to avoid problems if data is cached multiple times with conflicting expirations.

Here are the ways you can set the max value of a cache. You must set a max value to turn on caching.

// Configure Cache maximum size in the constructor
var myCache = new Y.Cache({max:5});

// Set the maximum size at runtime
myCache.set("max", 10);

Cache key/value pairs with the add() method.

// Add entries to the Cache
myCache.add("key1", "value1");

Retrieve cached entries with the retrieve() method. If there is no match for the given key, then null will be returned. Cached entries contain the properties request, response, cached, and expires.

// Retrieve a cached entry
var cachedEntry = cache.retrieve("key1");

By default, cached entries may contain duplicate keys: if you add an entry for request "foo" with value "bar" and then add another entry for request "foo" with value "bat", the cache will contain both entries. Retrieving an entry for request "foo" will only retrieve the newest value. However, setting uniqueKeys to true will validate for the uniqueness of keys stored in the cache.

// Enforce unique keys in the constructor
var myCache = new Y.Cache({max:5, uniqueKeys:true});

// Enforce unique keys at runtime
myCache.set("uniqueKeys", true);

A cache may be flushed of all its entries with the flush() method.

// Flush the cache
myCache.flush();

Offline caching

The CacheOffline cache extends basic caching functionality by storing data in the HTML5 localStorage object on browsers where that is supported, so that data can be available when the browser is offline and can persist across browser sessions. In cases where HTML5 localStorage is not available (i.e., IE 6 and IE 7), the functionality falls back to basic caching in local JavaScript memory.

var myCache = new Y.CacheOffline();

Use the following Attributes to configure your CacheOffline instance:

Attribute Default Description
sandbox "default" A unique identifier used to sandbox each cache instance's entries from other entries. This string persists across browser sessions so take care that it is not dynamically generated.
expires 86400000 By default, data will expire one day after it is cached. This Attribute accepts a Data value, or a number of milliseconds.
max null Read-only. This Attribute is disabled for CacheOffline — there is no notion of capping the number of entries in a cache. Each browser implements a maximum localStorage byte size.
uniqueKeys true Read-only. This Attribute is disabled for CacheOffline. All stored keys are unique.

Cache as a plugin

Use the plug(Y.Plugin.Cache) method on a host object to enable caching. The Y.Plugin.Cache class is available in the "cache-plugin" submodule.

// Define a max value to enable plugging.
myWidget.plug(Y.Plugin.Cache, {max:3});
myWidget.cache.add("key", "value");

The Cache plugin also accepts a cache value to enable you to point to any number of Cache implementations. Y.Cache and Y.CacheOffline are currently available.

// Define a max value to enable plugging.
myWidget.plug(Y.Plugin.Cache, {cache:Y.CacheOffline});

The Y.Plugin.DataSourceCache plugin enables seamless caching of DataSource responses.

// Use a basic cache
myDataSource.plug(Y.Plugin.DataSourceCache, {
cache: Y.Cache, // this is the default, this line is not needed
max: 100
});

// Use the "cache" configuration property to enable offline caching
myDataSource.plug(Y.Plugin.DataSourceCache, {
cache: Y.CacheOffline,
sandbox: "my3HrCache",
expires: 10800000 // 3 hours
});

Once the DataSourceCache plugin is enabled, it handles caching and retrieval of values without the need for extra code. Furthermore, all the methods and properties of the Cache instance is available on the host's cache namespace.

// Flush myDataSource's cache.
myDataSource.cache.flush();

Events

Event When Properties available on the Event facade passed to handler
add Entry is added to the cache.
entry
The cached entry.
request Entry is requested from the cache.
request
The request value.
retrieve Entry is retrieved from the cache.
entry
The retrieved entry.
flush Cache is flushed. none
error CacheOffline only. Fired when an entry could not be added, most likely due to exceeding the browser quota for the localStorage object.
error
The error object.