ChocolateChip provides the data cache as a convenient way to store data in relation to a DOM node. The data cached can be a variable, string, boolean value, array, object or function. The cache can handle any of these types without any need to convert them to string or parse them for reuse. By its very nature, the cache stores values by value. In other words, it stores the value at the time it is cached. If that data changes outside the cache, the value in the cache remains unchanged. The cache uses a node as the key to the data being stored. There are two methods to use to handle the cache:

  • Element.cache()
  • Element.uncache()

To associate data with a node, just execute the cache method on the node and pass the data as the argument:

$.(function() {
    $('#user').cache({name: 'Joe', age: '21', job: 'athelete'});
});

After you have cached data on a node, you can retrieve it by simply executing Element.cache() without any arguments:

$.(function() {
    var data = $('#user').cache(); // returns the previous object
    // or you can access object members in the cache directly:
    var userName = $('#user').cache().name; // returns 'Joe'
    var userJob = $('#user').cache().job; // returns 'athelete'
});

To remove data from a node, you use Element.uncache():

$.(function() {
    $('#user').uncache();
});
Advertisements