Debugging:
// The meta data method will wrap around the data function, but use
// a single point of entry for our data so that we can get the key
// collection of no parameters are passed.
jQuery.fn.metaData = function(){
var strCollectionKey = "__metadata";
var objData = null;
var strKey = "";
var strValue = "";
// Check to see how many arguments were passed-in.
if (arguments.length == 0){
// Return the data collection for the first element in the
// jQuery collection.
// Get the meta data collection.
objData = this.data( strCollectionKey );
// Check to see if we have a data object yet.
if (!objData){
// Store an empty struct in the meta data.
this.data( strCollectionKey, {} );
}
// Return an meta data collection.
return( this.data( strCollectionKey ) );
} else if (arguments.length == 1){
// Return the value for the first element in the jQuery collection.
return( this.metaData()[ arguments[ 0 ] ] );
} else if (arguments.length == 2){
// Set the given name value. We will be doing this for each element
// in our jQuery collection.
// Create a local reference to the arguments (so that we can later
// refer to them in the each() method.
strKey = arguments[ 0 ];
strValue = arguments[ 1 ];
// Iterate over each element in the collection and update the data.
this.each(
function( intI, objElement ){
var jElement = jQuery( this );
// Get the meta data collection.
var objData = jElement.metaData();
// Set the values. Because the object is passed by reference,
// we don't need to re-store it.
objData[ strKey ] = strValue;
}
);
// Return the current jQuery object.
return( this );
}
}
$(
function(){
// Get a refernce to our button.
var jButton = $( "form :button" );
// Bind the initial click count.
jButton.metaData( "clickCount", 0 );
// Hook up the click handler.
jButton.click(
function( objEvent ){
// Get the current click count.
var intCount = jButton.metaData( "clickCount" );
// Increment the click count.
intCount++;
// Store it back in the button data and store the
// time at which the button was clicked.
jButton
.metaData( "clickCount", intCount )
.metaData( ("click" + intCount), new Date() )
;
// Update the button display.
jButton.val( "Click Me ( " + intCount + " )" );
// Debug meta data.
DebugMetaData( jButton );
}
);
}
);
// I debug the given meta data element.
function DebugMetaData( jObject ){
var jOutput = $( "#debug" );
var objData = jObject.metaData();
// Iterate over the data and output it.
$.each(
objData,
function( strKey, val ){
jOutput.append( strKey + " : " + val + "<br />" );
}
);
// Add another empty line.
jOutput.append( "<br />" );
}