jqueryjquery-data

Assign variable to $(this).data("whatever") or no?


Is there (performance/cpu) effort applied in reading values using jquery data() ?

So... I have several links/buttons, similar to the following

<a href='#' class='ui-btn' data-counter='1234'>test</a>

When the link is clicked, an event is executed. I need the value of counter more than once during the processing of the event. Should I just read the value from source every time (thus, use $(this).data("counter") ) or should I instead do

var counter=$(this).data("counter");

and reference counter everywhere?


Solution

  • It's entirely up to you, but work is required every time you call $(this).data("counter"). It probably doesn't matter, but grabbing it to a local will be shorter to type in the long run and save the odd microsecond.


    Note that unless you really need the features of data, you might want to use attr instead: +$(this).attr("data-counter") (the + at the beginning converts from string to number, which data does for you with all-digits strings). data is not an accessor for data-* attributes, it's an accessor for jQuery's data cache for that element. The first time you call it on an element, it creates the cache and populates it from all the data-* attributes on the element, and then keeps a copy of them as they were at that moment. (And using it as a setter doesn't change the attribute, nor does changing the attribute after you've used data on the element change data's copy of the values.) attr is just an accessor for attributes.