Leverating YAHOO.env._id_counter for Unique Ids

This topic was originally covered in the Unique Id Generator article, where you can find more a heavy-handed solution, allowing a developer to determine the character set used for and length of the generated id. However, as most of the commenters pointed out, there is a simpler way to create unique numbers that will work for most developers; that is to increment a global number each time it is used. YUI already has a counter for this YAHOO.env._id_counter, which they use to generate unique IDs in the YAHOO.util.Dom.getUniqueId function (and probably other places). However, they havent exposed a good API to leverage this variable without directly accessing the pseudo-private _id_counter variable.

So the first task is to write a function to return and increment the _id_counter variables.

Example 1: getNextIdCounter

getNextIdCounter: function() {
	return YAHOO.env._id_counter++;

This function returns the current value of the counter, before incrementing the counter. If you use the YUI-EXT-MVC framework, this has been added to the end of yahoo-ext/lang.js, where YAHOO.env is augmented; I may move the YAHOO.env augmentation into its own file at some point, when I migrate the browser detection functions off of YAHOO.lang.

Now we can write a new version of getUniqueId, using getNextIdCounter to generate the id. This has also been added to YAHOO.lang in yahoo-ext/lang.js.

Example 2: getUniqueId

getUniqueId: function(prefix, isNotInDOM) {
	var pfx = prefix || yui-gen, id;

	do {
		id = pfx + _YEVN.getNextIdCounter();
	while (isNotInDOM && document.getElementById(id));

	return id;

Calling getUnqueId will return a string, yui-gen#, where # is the latest value of _id_counter. Using the first argument a developer can provide their own prefix, instead of yui-gen. And if they are worried that a given ID might exist in the DOM, simply set isNotInDOM to true and the function iterates until a valid ID is found. It is that simple.

The value of the getNextIdCounter function is that it wraps the environment variable, so that the developer does not have to manage incrementing _id_counter when they use it. This allows YUI-EXT-MVC to leverage the same uniqueness generator as YUI, instead of duplicating it.

These methods are available at yahoo-ext/lang.js.