Get div object containing jquery widget inside widget

I have the following code:

<div id="widHolder"></div> <script type="text/javascript" language="javascript"> $('#widHolder').widgetName({ optionOne: false, optionTwo: 1, onComplete: function (holder) { // ... do something here with the 'widHolder' object such as $(holder).addClass(x,y) } }); </script> 

Inside the widget itself, the onComplete method will be called immediately after the widget is fully initialized. I want the code inside the widget to refer to the object that the widget is associated with (in this case, the div with the id "widHolder").

My goal is to be able to quickly and easily refer to the holding object, creating the incomplete function mentioned above. The code in the widget itself will simply call the onComplete function, passing the holder (which I need to get) as a parameter.

Here is sample jQuery UI Widget plugin code

 (function ($) { $.widget("ui.widgetName", { options: { // ... other options that can be set onComplete: undefined }, // called on the initialization of the widget _init: function () { // do initialization functions... if(this.options.onComplete) this.options.onComplete( I_WANT_TO_SEND_THE_DOM_ELEMENT_HERE ); }, } }) 
+4
source share
2 answers

The jQuery UI Factory widget allows an element to access through:

this.element using the plugin.

For more information, please have a look here: http://wiki.jqueryui.com/w/page/12138135/Widget%20factory

Does this answer your question better?

 (function ($) { $.widget("ui.widgetName", { options: { // ... other options that can be set onComplete: undefined }, // called on the initialization of the widget _init: function () { // do initialization functions... if(this.options.onComplete) this.options.onComplete( this.element ); }, } }) 

Side note. If you create another closure inside your plugin, you need to keep a link to this . For instance:

 (function ($) { $.widget("ui.widgetName", { options: { // ... other options that can be set onComplete: undefined }, // called on the initialization of the widget _init: function () { // do initialization functions... var self = this; $.each(an_array_or_something_obj, function(){ //here this will refer to the current element of the an_array_or_something_obj //self will refer to the jQuery UI widget }); if(this.options.onComplete) this.options.onComplete( this.element ); }, } }) 
+6
source

Use this.offsetParent if, as in your example, the holder is the direct parent of the widget.

0
source

Source: https://habr.com/ru/post/1392392/


All Articles