When I first learned about the jQuery data() method, it totally blew my mind. The ability to store data associated with an element in a way that doesn't hack the XHTML was just brilliant! But, I feel that there is something just slightly lacking from the data() method - the ability to gather all the stored values as a collection. The way data() works now, you can either set the value of or get the value of a given key; if you have multiple values associated with a given element, you have to make multiple calls to the data() method to retreive them.
I figured it would be nice to have the option to pass the data() method no arguments and get back the entire set of associated data (in name-value pairs).
- 0 Arguments :: Get entire data set of first element.
- 1 Arguments :: Get given data point of first element.
- 2 Arguments :: Set given data point for entire collection.
To create this functionality, I built the metaData() plugin which wraps around jQuery's core data() method and adds the zero-argument option. This plugin was covered in my Intensive Exploration of jQuery presentation, but I thought it would be nice to cover it here as well as an example of how to build a jQuery plugin:
What I really like about this plugin is that it not only leverages an existing part of the jQuery core library (the data() method), but that it calls itself recursively to handle the various argument options.
Now that we have our plugin defined, let's run a little test to see how it works:
As you can see in the demo, we are making three independent calls to the metaData() method to set data points. However, when we output the data, we make a call to metaData() with no arguments so as to get the entire collection. Running the above code, we get the following output:
created : Thu Mar 05 2009 14:25:01 GMT-0500 (Eastern Standard Time)
location : http://......./testing/jquery/meta_data.htm
userAgent : Mozilla/5.0 Gecko/2009011913 Firefox/3.0.6
While it's not that often that we need to output an entire collection of data within an application, I have found this plugin to be extremely useful when it comes to debugging jQuery scripts:
console.log( $( "...." ).metaData() );
jQuery is so awesome and so easy to extend! I love you jQuery.
Want to use code from this post? Check out the license.