you-dont-need-jquery
you-dont-need-jquery copied to clipboard
$.fn.data isn't just for string values
That's a major difference with dataset.
A solution would be to use a weak map to link DOM elements to maps (as is done here).
@Canop That function has no access to the DOMs data attributes though, only new ones that are set.
Unless I am missing something?
You're missing nothing. What I meant is that when you're not interested in the string value, which is mostly when you're not interested in the data attributes but in mapping some data to DOM elements, then you can use a weak map. The code I linked to is exclusively used in that case (and shouldn't be linked to in the main page, it's just an illustration of what I mean for the purpose of this issue).
In real code snippet I think you're either interested in the data-attribute (which is bad practice in my book) or in mapping dom elements to data. We should cover both cases but not with the same code (one is covered with dataset, the other one with a weak map).
I'm tempted to just remove the jQuery data method, and make the jQuery version do $(myElement).attr('data-foo', whatever), since the data method doesn't actually apply an attribute to the DOM.
attr is only for string values, so it's not suited.
Aye, but so is dataset, right? Data attributes are just regular 'ol attributes that store strings. That's all I'm trying to compare; I don't feel an urgent need to cover 100% of what jQuery does.
I don't think anybody use $.fn.data just for the useless data attributes. If you want to tell how to avoid using jquery, then IMO you should explain how to safely map data to elements.
wouldn't something like the following be suitable?
myElement.data = new Map;
myElement.data.set('foo', bar);
Or are you thinking of something else?
This is a solution, but it involves adding properties to native elements, which I personally dislike and which isn't guaranteed to be safe, that's why I'm using a weak map (see first comment in this page, with link to a trivial implementation).