views:

622

answers:

4

My GWT application creates text areas, each of which must have an ID in order to be useful to a third-party JavaScript library. I know how to assign an ID to a GWT widget; I'm after a good way of generating those unique ID's.

+1  A: 

I believe this would be what you need for unique identifiers ( using a timestamp and the 'widget-' namespace ).

'widget-' + (new Date).valueOf()
meder
+2  A: 

Java has a built-in class for unique ID creation: http://java.sun.com/j2se/1.5.0/docs/api/java/util/UUID.html

Another common way is by using a timestamp, i.e. System.currentTimeMillis()

harto
UUID is not implemented by GWT, but I found a guide for how to provide an implementation of your own: http://code.google.com/webtoolkit/doc/1.6/DevGuideOrganizingProjects.html#DevGuideModuleXmlI also found an implementation: http://2ality.blogspot.com/2009/01/uuids-for-gwt.htmlThanks for the headstart.
David
No worries! Btw, it looks like Chi's answer might be even more suitable for your purposes.
harto
Yes, I think you're correct: HTMLPanel.createUniqueId seems to be exactly what I'm after.
David
Be careful using System.currentTimeMillis(), on many systems the granularity of the call is not precise up to the millisecond, and you end up with the same value even when called several milliseconds apart. Anyway, you can never ensure you will not have twice the same ID using that. A global counter you increment is probably much safer if you can afford to share it.
lOranger
+1  A: 

Javascript:

var idIndex = 0;

function getNewId() {
    return "textGWT"+(idIndex++);
}

Java:

class IdMaker {

    private static int idIndex = 0;

    public static String generate() {
        return "textGWT"+(idIndex++);
    }
}
Julian Aubourg
+4  A: 

For GWT, take a look at HTMLPanel.createUniqueId

String id = HTMLPanel.createUniqueId();
Chi