Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create unique id's for jQuery widget instances?

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?

like image 832
Carlo Roosen Avatar asked Jul 16 '12 12:07

Carlo Roosen


2 Answers

You can use a closure:

(function () {
  var textEditorCount;
  $.widget("myEditor.textEditor", {
     _create: function () {
        textEditorCount = textEditorCount ? textEditorCount + 1 : 1;
        this.instanceID = textEditorCount;
     },
     ...
  };
})();

textEditorCount is not going to be global anymore.

like image 141
Inkbug Avatar answered Nov 15 '22 09:11

Inkbug


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').

like image 24
Victor Avatar answered Nov 15 '22 08:11

Victor