Sunday, November 28, 2010

jQuery’s Data Method – How and Why to Use It

jQuery’s data method gives us the ability to associate arbitrary data with DOM nodes and JavaScript objects. This makes our code more concise and clean. As of jQuery 1.4.3 we also have the ability to use the method on regular JavaScript objects and listen for changes, which opens the doors to some quite interesting applications.

Behind the Scenes

Internally, jQuery creates an empty object (called $.cache for the curious), which is used to store the values you set via the data method. Each DOM element you add data to, is assigned a unique ID which is used as a key in the $.cache object.
jQuery does not store only user-created data in that cache. It also stores internal information and the event handling functions that you attach with live(), bind() and delegate(). Having centralized data storage makes jQuery’s codebase much more robust and bug free, something that we all can benefit from.

To Wrap it Up

The data method is just one of jQuery’s numerous utilities, which make the life of the web developer easier. Combined with the rest of the library’s abilities, it adds up to a solid foundation we can build upon.

http://tutorialzine.com/2010/11/jquery-data-method/

No comments: