How can I create unique id's for jQuery widget instances?
instance, jquery, unique, widget
Solution
Since jQuery UI 1.9 each widget instance has unique fields `this.uuid` and `this.eventNamespace`:
this.uuid = uuid++;
this.eventNamespace = "." + this.widgetName + this.uuid;
https://github.com/jquery/jquery-ui/blob/1.9.0/ui/jquery.ui.widget.js#L215
Field `this.eventNamespace` is suitable for assigning/clearing unique event handlers (http://api.jquery.com/on/ - read chapter 'Event names and namespaces').
Problem
I am creating a rich text editor based on jQuery widget, and it can have multiple instances on a page. The first instance should generate a toolbar like this: ``` <input type="checkbox" id="bold-1"><label for="bold-1">.. <input type="checkbox" id="italic-1"><label for="italic-1">.. ... ``` The second instance should generate: ``` <input type="checkbox" id="bold-2"><label for ="bold-2">.. <input type="checkbox" id="italic-2"><label for ="italic-2">.. ``` The labels 'for' attribute need to uniquely refer to their corresponding input 'id' attribute. Therefore I need to add a unique id for each instance. Something like this could work but I dont like to store a counter in global namespace: ``` var textEditorCount; $.widget("myEditor.textEditor", { _create: function () { textEditorCount = textEditorCount ? textEditorCount + 1 : 1; this.instanceID = textEditorCount; }, ... }; ``` Maybe the question boils down to: (How) can I store a variable in the namespace of the widget?