5

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?

2
  • Personally I would create global jquery array holding reference to all of my plugin instances. Then you can use .length to get number of them and easily reference needed one. Commented Jul 16, 2012 at 12:55
  • @fliespl You solution does work, but is a bit more than I need. My problem is not so much how to bind the button to the widget instance, but how to create a 'for' tag in the label that refers uniquely to an input id. Commented Jul 16, 2012 at 13:02

3 Answers 3

6

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.

1
  • Wow, yes of course. I have that closure already there, I just didn't think about declaring the variable there. Thanks a lot! Commented Jul 16, 2012 at 14:05
5

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

1
  • Thanks Victor, definitely the better solution Commented Aug 28, 2013 at 14:34
0

Global Var ( or in NS) Up one every instance that is what i do

1
  • so the remaining question is, how do I do that in the namespace. Can I just do: $.myNamespace.textEditorCount += 1; ? It seems to work, but I don't know if it is legal / advisable. Commented Jul 16, 2012 at 13:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.