$("#header").data('headerSettings',{
color: "red",
cost: "$25.00",
time: 1000
});
Now you could access that data anywhere else on the page:
$("#header").data('headerSettings').color;
In this recipe, we iterate over both an array and an object using
$.each(), which provides an elegant interface to the common task
of iteration. The first argument to the
$.each() method is the array or object to
iterate over, with the second argument being the callback method that is
executed for each element. (Note that this is slightly different from
the jQuery collection method
$('div').each(), whose first argument is the
callback function.)
When the callback function defined by the developer is executed,
the this variable is set to the value
of the element currently being iterated. Thus, the previous recipe could
be rewritten as follows:
(function($) {
$(document).ready(function() {
var months = [ 'January', 'February', 'March', 'April', 'May',
'June', 'July', 'August', 'September', 'October',
'November', 'December'];
$.each(months, function() {
$('#months').append('<li>' + this + '</li>');
});
var days = { Sunday: 0, Monday: 1, Tuesday: 2, Wednesday: 3,
Thursday: 4, Friday: 5, Saturday: 6 };
$.each(days, function(key) {
$('#days').append('<li>' + key + ' (' + this + ')</li>');
});
});
})(jQuery);
The Basics
You can call the data method on a jQuery object, or you can use the $.data() function instead.
2 | $( "#myDiv" ).data( "key" , "arbitrary value" ); |
5 | $.data($( "#myDiv" ).get(0), "key" , "arbitrary value" ); |
The data function is a low level implementation, and is actually
being used by the method call behind the scenes. The method call is also
more convenient, as it allows you to include it as a part of a chain.
Also, notice that you need to pass a
DOM element as
the first parameter of $.data, and not a jQuery object. This is why in
this article, we are going to concentrate on using the method call
instead.
When you use the data method, you need to pass two parameters – a key
and a value to be stored. The key has to be a string, and the value can
be any data structure, including functions, arrays and objects. There
is an alternative syntax, in which you pass an object as a single
parameter:
2 | $( "#myDiv" ).data({ "name" : "Stevie" , "age" :21}); |
5 | $( "#myDiv" ).data( "name" , "Stevie" ).data( "age" ,21); |
Now that you’ve inserted your data, you can read it by calling the data method with a single parameter – the key:
1 | var theValue = $( "#myDiv" ).data( "age" ); |
You can access the data everywhere in your script. It doesn’t matter
what the selector is, as long as it is the same element, you will get
the same value you’ve put in:
3 | var theValue = $( "div:first" ).data( "name" ); |
5 | $( "div:first" ).click( function (){ |
6 | alert($( this ).data( "age" ); |
As of jQuery 1.4.3 HTML5 data- attributes are also made available via
the data method. This means that if you have an element like this:
1 | < img id = "img1" data-internal-id = "221" width = "100" height = "100" /> |
You can access the data-internal-id attribute by just calling
$("#img1").data('internal-id')
, which is really useful in AJAX applications. We also used this technique in last week’s tutorial –
Making Better Select Elements with jQuery and CSS3.
Using the Data Method on JavaScript objects
You may find it surprising that you can use the data method on
regular JavaScript objects. This functionality has been around for some
time, but with jQuery 1.4.3 it opens the doors to some useful
applications.
2 | $(myObj).data( "city" , "Springfield" ); |
What the snippet above does, is actually create a city property on the object. But why not just set
myObj.city = "Springfield"
yourself? Because the data method triggers a number of useful events you can listen for:
03 | $(progressBar).bind( 'setData' , function (e,key,value){ |
06 | $( "#progress" ).width(value+ "%" ); |
07 | $( "#percentText" ).text(value+ "%" ); |
11 | $( "#progress" ).css( "color" ,value); |
15 | $( '#progress' ).toggleClass( "active" ,value); |
20 | $(progressBar).data( "enabled" , true ).data( "percent" ,21).data( "color" , "green" ); |
23 | console.log(progressBar.enabled); |
In the fragment above, we use the data method to create a simple API
with which we can update a progress bar on screen. The best part of it
is that at any given time you can just take a peek at the progressBar
object and get the current values.
There are two other events that are triggered when using the data method on a plain object:
- getData – triggered before data is read from the
object. You can use the return statement within the event handling
function to override the value. Can be used to run calculations behind
the scenes;
- changeData – triggered whenever data is set or changed. It is used in the jQuery datalink plugin
and allows you to bind a form to a JavaScript object and access the
form fields as properties of that object. This way you don’t have to
deal with reading and setting values, which is quite a burden especially
in longer forms. You can see it in action in the demo page.
Click on a row to access customer data using .data()
<br /><br />
<table style="width:400px;">
<thead style="background-color:#efefef">
<tr>
<td>Name</td>
<td>City</td>
</tr>
</thead>
<tbody id="tableBody"></tbody>
</table>
var $tbody;
$(document).ready(function () {
//Simulate Ajax call here to get customer data
var custs = getCustomerData();
$tbody = $('#tableBody');
for (var i = 0; i < custs.length; i++) {
var $tr = $('<tr><td>' + custs[i].Name + '</td><td>' + custs[i].City + '</td></tr>');
//Associate customer data with the row
$tr.data('custData', custs[i]);
//NOTE: Not generally efficient to manipulate the DOM in a loop
//if you have a large number of rows
$tbody.append($tr);
}
//Handle row click
$tbody.on('click', 'tr', function () {
//Get to row data
var custData = $(this).data('custData');
//Show State
alert('Name: ' + custData.Name + '\r\nState: ' + custData.State + '\r\nCity: ' + custData.City);
});
});
function getCustomerData() {
return [
{ ID: 1, Name: 'John', City: 'Scottsdale', State: 'AZ' },
{ ID: 2, Name: 'Jane', City: 'Chandler', State: 'AZ' },
{ ID: 3, Name: 'Michelle', City: 'San Diego', State: 'CA' },
{ ID: 4, Name: 'James', City: 'Portland', State: 'OR' },
{ ID: 5, Name: 'Tom', City: 'Dallas', State: 'TX' },
];
}
No comments:
Post a Comment