Bug Tracker

Opened 7 years ago

Closed 7 years ago

Last modified 7 years ago

#14523 closed bug (notabug)

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

Reported by: mike@… 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 7 years ago by Rick Waldron

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.

Last edited 7 years ago by Rick Waldron (previous) (diff)

comment:2 Changed 7 years ago by mike@…

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

comment:3 in reply to:  2 Changed 7 years ago by Rick Waldron

Replying to 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.

Note: See TracTickets for help on using tickets.