Skip to main content

Bug Tracker

Side navigation

#14523 closed bug (notabug)

Opened November 07, 2013 11:28PM UTC

Closed November 07, 2013 11:56PM UTC

Last modified November 08, 2013 12:29AM UTC

Accessor signatures of $.fn.data() have a side effect

Reported by: mike@mikepennisi.com 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.

Attachments (0)
Change History (3)

Changed November 07, 2013 11:56PM UTC by rwaldron comment:1

_comment0: 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 \ \ > 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).1383868701349370
resolution: → notabug
status: newclosed

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

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).

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.

Changed November 08, 2013 12:08AM UTC by mike@mikepennisi.com comment:2

Actually, jQuery's refusal to re-read the data-* attribute is the side effect I was referring to.

Changed November 08, 2013 12:29AM UTC by rwaldron comment:3

Replying to [comment:2 mike@…]:

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.