views:

35

answers:

2

I am building custom jquery widgets by extending dialog widget. How can I access widget itself and its functions from button press event function?

$.widget("ui.ImageLibrary", $.ui.dialog, {
   options: {
    title:'Choose Image',
    buttons:{
      "Ok":function(){
        // How can I access _somePrivateFunction here?
      },
      "Close":function(){
        //
      }    
    }
  },
  _somePrivateFunction: function(){
  },
  ...
+1  A: 
T.J. Crowder
no, in this case this will reference dialog element, but not dialog widget instance.
codez
@codez: Ah, okay, I must have mis-skimmed that tutorial. Then the second option I added while you were commenting would be the way to go. :-) (For me it's the way to go *anyway*...)
T.J. Crowder
+1  A: 

You can access the function by accessing the copy that was stored when you created this instance of the widget, like this:

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

You can give it a try here.

Another method, if it's an option, is to make it accessible via the widget bridging that happens (if people are overriding the button arguments, it'll need to be accessible anyway), like this:

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

You can give it a try here. The difference is obviously it's not strictly private anymore, but if someone else needs to change what that "ok" button does, would you maybe want it exposed anyway? Something to keep in mind overall, so just tossing this out there.

Nick Craver
thanks, perfect answer.
codez