#14523 closed bug (notabug)
Accessor signatures of $.fn.data() have a side effect
Reported by: | Owned by: | ||
---|---|---|---|
Priority: | undecided | Milestone: | None |
Component: | unfiled | Version: | 1.10.2 |
Keywords: | Cc: | ||
Blocked by: | Blocking: |
Description
When used as a getter, $.fn.data
will "fall back" to the DOM data-
attribute. Additionally, it will save this value to the internal data lookup
table for that element. This means that $.fn.data
is an accessor with a side
effect.
var $el = $( "<div>" ); $el.attr( "data-john", 23 ); $el.data( "john" ); // 23 $el.attr( "data-john", 45 ); $el.data( "john" ); // 23
This behavior is surprising--querying the state of the element changes it.
Granted, the API documentation contains a caveat about this detail:
The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery).
...but one could argue that the need for such documentation is a sign of an unintuitive interface.
Modifying this behavior would certainly be a breaking change, but I believe it is in jQuery's interest to implement an API that is consistent and easy to reason about.
Change History (3)
comment:1 Changed 9 years ago by
Resolution: | → notabug |
---|---|
Status: | new → closed |
comment:2 follow-up: 3 Changed 9 years ago by
Actually, jQuery's refusal to re-read the data-*
attribute is the side effect I was referring to.
comment:3 Changed 9 years ago by
Replying to [email protected]…:
Actually, jQuery's refusal to re-read the
data-*
attribute is the side effect I was referring to.
In that case, you're absolutely right. Apologies for the misinterpretation—I thought you meant that data
was overriding the attr value.
jQuery.fn.data only _reads_ from data-* attributes one time and never again, as described in the documentation: http://api.jquery.com/data/#data-html5
EDIT: Note there is no side effect of accessing a value: http://jsfiddle.net/rwaldron/5RLb7/ What you observed was jQuery's refusal to re-read that element's data-* attributes.