Sometimes it's useful to store arbitrary data with a particular node or object. If your class uses the Attribute utility, you're in luck and you're job is done. However, the Node class doesn't (yet) use the Attribute utility, so this port of the jQuery data storage API allows you to associate data with a particular Node instance. In fact, you're not limited to a Y.Node instances -- any object will do.
For Y.Node and Y.NodeList instances, two methods -- data() and removeData() -- are added to their prototypes and chainable so you can easily store and retrieve data you want to associate with those elements.
Example
Here's a simple example:
Click a link below to see things happen...
The code below is all you need. You'll also notice that I'm using a script to automatically load the data storage module from the Yahoo! CDN. See Dav Glass's blog for more information or you can just wait for YUI 3.1, in which case you won't need this script because it's built in.
Notes
The data and removeData methods are chainable except when they return data.
Methods
Y.DataStorage.data(obj) and Y.Node.data()
Retrieve all data for a particular object or Y.Node instance. If there is no data, this will return an empty object.
Y.DataStorage.data(obj, key) and Y.Node.data(key)
Retrieve keyed data for a particular object or Y.Node instance. If there is no data, this will return undefined.
The key should be a string, but it can be a path (e.g. "key.subkey") and the path will be traversed. If the subkey can't be found, the keyed data will be returned.
Y.DataStorage.data(obj, key, value) and Y.Node.data(key, value)
Set a keyed piece of data for a particular object or Y.Node instance.
Y.DataStorage.data(obj, values) and Y.Node.data(values)
Set the data object for a particular object or Y.Node instance.
Y.DataStorage.removeData(obj) and Y.Node.removeData()
Remove all of the data for a particular object or Y.Node instance.
Y.DataStorage.removeData(obj, key) and Y.Node.removeData(key)
Remove a keyed piece of data for a particular object or Y.Node instance.
| < Prev | Next > |
|---|



YUI Gallery Data Storage

