Jump to content

How to attach objects and data to DOM with jQuery.data to avoid memory leak issues

+ 1
  sarahkim's Photo
Posted Jun 17 2010 03:09 PM

Properties added to an object or DOM node at runtime (called expandos) exhibit a number of issues because of flawed garbage collection implementations in some web browsers. This excerpt from jQuery Cookbook shows you how to avoid memory leak issues by using .data().

Given the following DOM code:

var node = document.getElementById('myId');
node.onclick = function() {
    // Click handler
node.myObject = {
    label: document.getElementById('myLabel')

you have metadata associated with a DOM element for easy reference. Because of flawed garbage collection implementations of some web browsers, the preceding code can cause memory leaks.

jQuery provides developers with an intuitive and elegant method called .data() that aids developers in avoiding memory leak issues altogether:

$('#myId').data('myObject', {
    label: $('#myLabel')[0]
var myObject = $('#myId').data('myObject');

The .data() method manages access to our data and provides a clean separation of data and markup.

One of the other benefits of using the data() method is that it implicitly triggers getData and setData events on the target element. So, given the following HTML:

<div id="time" class="updateTime"></div>

we can separate our concerns (model and view) by attaching a handler for the setData event, which receives three arguments (the event object, data key, and data value):

// Listen for new data
$(document).bind('setData', function(evt, key, value) {
    if ( key == 'clock' ) {
        $('.updateTime').html( value );

The setData event is then triggered every time we call .data() on the document element:

// Update the 'time' data on any element with the class 'updateTime'
setInterval(function() {
    $(document).data('clock', (new Date()).toString() );
}, 1000);

So every 1 second (1,000 milliseconds) we update the clock data property on the document object, which triggers the setData event bound to the document, which in turn updates our display of the current time.

jQuery Cookbook

Learn more about this topic from jQuery Cookbook.

Getting started with the jQuery library is easy, but it can take years to fully realize its breadth and depth; jQuery Cookbook shortens the learning curve considerably. You'll learn patterns and practices from 19 leading developers who use jQuery for everything from integrating simple components into websites and applications to developing complex, high-performance user interfaces. The recipes start with the basics and then move into practical use cases with tested solutions to common web development hurdles.

See what you'll learn

0 Replies