Wednesday, September 9, 2009

jQuery Tip: Storing and Retrieving Object Properties with the Data() Function

The jQuery data() function allows you to store data "within" a DOM object by associating a property name with a value.  The first line of the code below assigns the value "bar" to the property name "foo" associated with the <form> element on the page, while the second line retrieves the stored value:

$("form").data("foo","bar");
...
var fooValue= $("form").data("foo");

It's a useful technique for adding metadata to a DOM element.

The jQuery plugin I'm currently working on associates several pieces of metadata with certain DOM elements on the page.  It occurred to me yesterday that it might be cleaner to store all of that metadata under one property (one namespace) in the DOM element, reducing the possibility of my plugin interfering with any other code might also store data using the data() function.  But I wasn't quite sure how I would retrieve the individual metadata values.

Turns out the solution is quite simple:  you can retrieve the object sorted in the namespace property, then reference the individual properties within the namespace using dot notation:

  var settings= {
     denoteDirtyForm: true,
     denoteDirtyOptions:false,
     trimText:true,
     dirtyFieldClass:"changedField"
  }
  ...
  $("form").data("myNamespace",settings);
  ...
  var showDirtyForm= $("form").data("myNamespace").denoteDirtyForm;
  var dirtyClass= $("form").data("myNamespance").dirtyFieldClass;

So it looks like there's no real limit to the amount or complexity of data you can associate with a DOM element using data().

No comments:

Post a Comment