Determine if jQueryUI Widget Element

I wrote a jquery-ui widget using a Factory widget ...

I need to be able to determine whether the widget is already in the code or not ...

My investmentGrid widget is being created on #container with

$('#container').investmentGrid() 

I need to be able to determine elsewhere in the code if $ ('# container') is already an investmentGrid

+6
jquery-ui widget
source share
5 answers

You can query the jQuery.data() element, for example:

 if ($('#container').data('investmentGrid')) { ... } 
+6
source share

You can try the pseudo selector created for you using the factory widget. $(":namespace-widgetname")

+5
source share

@ dan-story may have received an answer the moment he answered it, but I found that this method no longer works. Well, not quite. At least not with jQueryUI 1.10. According to the documentation http://api.jqueryui.com/jQuery.widget/ in the "Instance" section, now you need to have the full name of the widgets.

For example, if you create your factory widget as follows:

 $.widget("Boycs.investmentGrid", ...); 

Then, to check if the container has it, you should check this:

 if ($('#container').data('Boycs-investmentGrid')) { ... } 

Itโ€™s not enough to just use a name.

+3
source share

@Boycs: In my opinion, using Widget Factory protects you from instantiating the plugin several times on the same element. (ref: http://jqueryui.pbworks.com/widget-factory )

In addition, if you want to confirm that the โ€œcontainerโ€ is already an investment grid, you can try the following code inside your plugin code:

this.element.data ("investmentGrid") === this;

For more information, you can refer to docs.jquery.com/UI_Developer_Guide

+1
source share

Current versions of jQuery UI (I can confirm this with 1.11.x) allow you to query an instance of a widget using the instance() method. It will look like this:

 $('#container').investmentGrid('instance') 

If the item does not have an investmentGrid widget assigned, you will get undefined back.

Instead, you can use the call:

 $(#container').is(':data("namespace-investmentGrid")') 

This has the advantage that it also works, even if the widget is not loaded.

+1
source share

All Articles