How can I access the widget and its functions from other areas?

I create custom jquery widgets by expanding a dialog widget. How can I access the widget itself and its functions from the button event event function?

$.widget("ui.ImageLibrary", $.ui.dialog, { options: { title:'Choose Image', buttons:{ "Ok":function(){ // How can I access _somePrivateFunction here? }, "Close":function(){ // } } }, _somePrivateFunction: function(){ }, ... 
+4
source share
2 answers

You can access this function by referring to the copy that was saved when creating this instance of the widget, for example:

 "Ok":function(){ $.data(this, "ImageLibrary")._somePrivateFunction.call(this); } 

Here you can try here .

Another way, if this is an option, is to make it accessible via a bridge using a widget (if people override button arguments, this should be available in any case), for example:

 $.widget("ui.ImageLibrary", $.ui.dialog, { options: { title:'Choose Image', buttons:{ "Ok":function(){ $(this).ImageLibrary("someFunction"); }, "Close":function(){ $(this).ImageLibrary("close"); } } }, someFunction: function(){ alert("test"); } }); 

Here you can try here . The difference is obviously not strictly confidential, but if someone else needs to change what this β€œok” button does, you probably want it to be set anyway? Something to keep in mind overall, so just drop it there.

+4
source

According to this tutorial , one option is to use this :

 "Ok": function() { this._somePrivateFunction(): } 

(The comment below codez states that this did not work, I must have looked at the tutorial incorrectly. However, below.)

Another option for truly private functions, however, would be to use the function to define the scope (closure) and local calls. It would also set to use named functions rather than anonymous ones , which is useful for debugging. Example:

 $.widget("ui.ImageLibrary", $.ui.dialog, (function(){ // ^-- This is the scoping function var pubs = {}; // Our public symbols pubs.options = { title:'Choose Image', buttons:{ "Ok": myWidgetOkClickHandler, "Close": myWidgetCloseClickHandler } }; function myWidgetOkClickHandler() { // Call your truly private function, ensure `this` is // set correctly (or just code trulyPrivateFunction to // expect it as an argument instead, aka procedural // programming) trulyPrivateFunction.call(this); } function myWidgetCloseClickHandler() { } function trulyPrivateFunction() { } // Don't forget this! return pubs; })()); 
+1
source

All Articles