r/javascript • • Dec 23 '13

jQuery .data() considered potentially harmful

http://thinkco.de/jquery-data-considered-potentially-harmful/
0 Upvotes

4 comments sorted by

18

u/davethegr8 Dec 23 '13

IMO articles like this could be considered potentially harmful. The main thing they seem to communicate is a lack of understanding about how things work.

The first thing to realize is that .data() and data-... are not equivalent. Naming convention problem perhaps, but you need to know this to write good JS.

Using .data() maps to jQuery's internal representation of what data that element contains, not what data- attributes are set on it. The reason for that is that DOM access is very slow, while storing things in memory is not.

Here's what the jQuery docs say:

Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute.

So, it maps to memory first and then falls back to data- attributes. This means that you get unexpected behavior, true. However what you need to know is that you can always rely on .data() calls from javascript, and if you ever really really need to look at or set the actual attribute use $.attr('data-...', value). There's no need to create a rule to use one or the other exclusively, just understand how they differ.

On the string / number thing, the docs say this:

A value is only converted to a number if doing so doesn't change the value's representation. For example, "1E02" and "100.000" are equivalent as numbers (numeric value 100) but converting them would alter their representation so they are left as strings.

So what if you don't get the exact data type back you put in? Javascript is a loosely typed language, and that means you can treat data types as other data types. Yes, if you're storing number like sequences you may need to cast them back to strings but you have to do that kind of thing all the time filtering user input.

Finally, I wasn't sure what you meant by "the same instance of jquery everywhere". Are you running multiple versions of jquery on one page? Because that's a terrible idea. Or that you have to use variables in the same scope because the data is tied to that? If you see this code, .data() is above scope issues.

$b = $('body')
$b.data('test', true);

(function () {
    var $b = $('body')
    $b.data('test', false);
    $('body').data()
})();

$('body').data()

3

u/morb6699 Dec 23 '13

This article is bad, and you should feel bad for posting it.

I kid, but really... there is a lot of misinformation or inaccurate information in that post.

3

u/[deleted] Dec 23 '13

Coupling your model to a piece of markup is generally harmful too. I'd avoid jQuery.data altogether.

1

u/brtt3000 Dec 23 '13

"considered harmful" is considered harmful.