An Id is unique.

… or at least should always be treated as such. There is no official function in Dojo for generating a unique ID, though is a very common task, and very simple to accomplish. In this ultra short cookie, we’ll create a reusable function for just this use case.

Feel free to drop this in anywhere you need to generate a unique id. The code is very small:

(function(d){
  // wrapped in this function to keep a local copy of some vars:
  var globalId, id_count = 0, base = "djid_";
  // the function:
  d.generateId = function(altBase){
     do{ globalId = (altBase || base) + (++id_count) }
     while(d.byId(globalId));
     return globalId;
  }
})(dojo);

We have private copies of a globalId string (the current most recent unique id), a private counter variable (id_count) and a base string to use for the prefix. By calling do{ }while() rather than while(){..} we ensure our loop is always run at least once. The condition is dojo.byId(globalId), which returns undefined if no node with that id is found. When we escape, return the string ID at first ‘failure’. Viola.

The altBase parameter to the function is optional. When it is undefined, the base from within our closure is used. Makes for a nice small practical example of the use of a closure, as well.

Tags: