It seems to me that jQuery’s .data() function is more of a write-once store than true read-write-storage.
There does not seem to be a comfortable way of updating complex values.
Let’s suppose one wants to use some elements in a double-linked list (not my use case, illustrative purpose only).
It would be easy if I would do:
$elem.data('prev', $prev);
$elem.data('next', $next);
But I feel it is bad practice to pollute the “global” .data() namespace of an element.
So I would rather do:
$elem.data('list', {prev: $prev, next: $next});
But how do I now update prev?
In the first example, I would just do:
$elem.data('prev', $newPrev);
But in the in my opinion “nicer” way of doing things the only thing I can think of is something like this:
$elem.data('list', {prev: $newPrev, next: $elem.data('list').next});
This seems a lot more cumbersome to me and I suspect there is a better way, but so far I was unable to find anything.
How should I go about this?
When you call jQuery’s data method with one argument, you get a reference to the stored object, which you can update directly using regular
.notation:Thanks @balpha