Reputation: 11545
Let's say I have to remember the initial height of certain element.
A common practice I see is to save this value with $.data
on that element.
I fail to understand the benefits of this. Why not simply keep a simple variable with that value, or an array with values if there are multiple elements? Keeps the code easy to understand.
Upvotes: 4
Views: 78
Reputation: 866
Basically because le you save information INSIDE A NODE, preventing possible variable name conflicts and without the need to pass variables around. All the needed informations about a node, stay with the node itself
Upvotes: 0
Reputation: 318232
The main reason for using data()
is to store data specific to a certain element so it can be accessed later, here's an example
$('.elements').on('click', function() {
$(this).data('value', this.value);
});
$('.elements').on('keyup', function() {
$(this).val( $(this).data('value') );
});
Note that the event handler could match a number of different elements, and using data()
keeps the data associated to each element without using several variables for each element or a complex array.
Upvotes: 6
Reputation: 943615
It allows the function to be reused to apply the same effect to other elements (without having to deal with closures).
It allows the value to be initialized with HTML.
It makes it easier for developer tools to inspect the data.
Upvotes: 4