r/javascript • u/callumacrae • Dec 23 '13
jQuery .data() considered potentially harmful
http://thinkco.de/jquery-data-considered-potentially-harmful/
0
Upvotes
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
Dec 23 '13
Coupling your model to a piece of markup is generally harmful too. I'd avoid jQuery.data altogether.
1
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()anddata-...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 whatdata-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:
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:
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.