jQuery Tip #3 - Using the data() Function

Interested in learning more about jQuery? Check out the jQuery Fundamentals course at Pluralsight.com.


Previous Tips:

Over the years of building Web applications I've often run into scenarios where I need to associate data with a div or table row so that I can easily retrieve it without going back to the server. For example, you might have a table full of customer rows and want to store address, city, customer ID and other data that may not be shown in the table. As the user clicks a row you can then pull the data stored with the row and show it in a dialog or another area of the page.

Before jQuery became all the rage developers would use custom attributes added to an element, JavaScript arrays, or other custom techniques to handle this task. If a single value needed to be stored then the id attribute would often be used assuming the value was unique. I’ve seen classes used when values weren’t unique. One technique I used way back in the day when multiple values needed to be stored on a node is show next. The code associates values with a given row node rather than relying on arrays that hold the data in JavaScript:

 

row.setAttribute('city', 'Scottsdale');
row.setAttribute('state', 'Arizona');


As the user clicks on a row calls to getAttribute('city') and getAttribute('state') can be used to retrieve the city and state values. Although this technique still works today, it's generally frowned upon especially given that there are better techniques that can be used. While you can always store data in JavaScript objects (or even use HTML5’s data- attribute), jQuery has a data() function that can be used to easily associate data with a given DOM object and even work with HTML5 data attributes. Here's what the official jQuery documentation says about the data() function:

"The .data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks."

Using the data() function is quite simple. For example, to associate a city value with a row (assume row represents a <tr> element), the following code can be used:

$(row).data('city', 'Scottsdale');


To retrieve the city value from a row you can write the following code:


var city = $(row).data('city');


The data() function can also be used to retrieve HTML5 data attributes from elements. Assume the following element exists in a page:

<div id="custContainer" data-city="Scottsdale" data-state="Arizona">
</div>

 

To retrieve the value of the data attributes the following jQuery code can be written:


var custDiv = $('#custContainer');
var city = custDiv.data('city');
var state = custDiv.data('state');


In addition to this functionality, the data() function also handles storing object literals which can be very useful. The following code shows an example of creating and storing an object literal that holds customer data:


var cust = {
    firstName: 'John',
    lastName: 'Doe',
    city: 'Scottsdale',
    state: 'Arizona'
};


$(row).data('customer', cust);


A more robust example of using data() can be found in the Account at a Glance sample application (download it from http://ow.ly/8VWk9). The following code demonstrates how data() can be used to store HTML rendered using client-side templates. This example doesn't use a string value to set the data key but instead uses two expando properties named templates and data respectively (both are custom properties).


var tileBinder = function () {
    var templateBase = '/Templates/',
    bind = function (tileDiv, data, renderer) {
        var tileName = tileDiv.attr('id');
        $.get(templateBase + tileName + '.html', function (templates) {
            $('body').append(templates);
            var acctTemplates = [
                tmpl(tileName, 'Small', data),
                tmpl(tileName, 'Medium', data),
                tmpl(tileName, 'Large', data)
            ];

            tileDiv.data().templates = acctTemplates;
            tileDiv.data().data = data;
            renderer(tileDiv);
        });
    },
    tmpl = function (tileName, size, data) {
        var template = $('#' + tileName + 'Template_' + size);
        if (data == null) return template.html();
        return template.tmpl(data);
    };

    return {
        bind: bind
    };
} ();


An example of accessing the template data is shown next:


var template = tileDiv.data().templates[0]; //grab the first template's HTML

 

You may wonder how data associated with a node can be removed if needed? jQuery provides a removeData() function that can be used to remove data from a given node. If you pass no parameters then all data will be removed from the node defined in the selector. If you supply a key that specific data value will be removed. The documentation states that using removeData() only affects data added using the data() function and that data- attributes will not be removed.


$(row).removeData(); //remove all data
$(row).removeData('customer'); //grab the first template's HTML



Live Example


If you’re interested in learning more about jQuery or JavaScript check out my jQuery Fundamentals or Structuring JavaScript Code courses from Pluralsight. We also offer onsite/online training options as well at http://www.thewahlingroup.com.




Conclusion

The data() function is extremely useful in a variety of situations and should definitely be used over adding custom attributes (unless they’re data- attributes) to DOM nodes. If you need to associate data with a row, div, or other element it provides a convenient way to do it with a minimal amount of code.


image

comments powered by Disqus

3 Comments

Comments have been disabled for this content.