Underneath the hood JQuery uses a map of "UUIDs" (just a counter it maintains as jQuery.uuid
) to work around the well-known memory leak issues browsers have when you attach a property to a tag in the DOM from Javascript. In lieu of doing so, JQuery uses the $.data(tag, name, value)
to store data in a map keyed off of the uuid (a key that can be determined by checking tag[jQuery.expando]
).
While $.data()
is very useful, there are times you want to map data to tags without dumping that data into one global bucket - you want your own smaller bucket of data that you can, for example, check the length of or loop through.
As a contrived example, suppose you have icons that rotate through one of 4 states when clicked. When one is in state 2, you want to add it to an array of icons in state 2. The most obvious way to do so is to add the tag to an array; however doing so would create a memory leak. You could call $.data()
on the checkbox, but that doesn't quite accomplish what you're trying to do - you'd have to loop through all the checkboxes checking $.data()
against them to figure out which are and aren't in the list.
You need to store some abstraction of the tags in an array, and that's jQuery's UUIDs. You could write your own UUID functionality, but ideally you just leverage the UUID functionality already built-in to JQuery for both code-size and quality reasons. You could ask JQuery to attach a UUID to the tag implicitly by calling $.data(tag, 'irrelevant', 1)
and then check tag[jQuery.expando]
to get its UUID, and finally use that in the list... but that's a bit of a hack. Really what would be ideal is to have the following exposed in the public API:
$.getUuid(tag)
: Checks for and creates a UUID if none exists - ideally the method is factored out of $.data()
and creates or fetches the uuid for the tag passed in.
So, is there a reason this isn't factored out into its own method in jQuery? Is this harmful in some way? Was it just never something that seemed useful?
I should note that I've actually factored it out in the version of jQuery we're using, and it's very helpful. But perhaps there's an underlying risk I'm not hitting in my usage. I'm also aware of a plugin that sort-of accomplishes this, but it's a bit broken - and having 2 codepaths to perform the same UUID functionality is both a bit wasteful and a bit brittle.