I am building custom jquery widgets by extending dialog wid开发者_如何学编程get. 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(){
},
...
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.
According to this tutorial, one option is to use this
:
"Ok": function() {
this._somePrivateFunction():
}
(In a comment below codez says the above doesn't work, I must have mis-skimmed the tutorial. The below does though.)
Another option for truly private functions, though, would be to use a scoping function (closure) and local calls. That would also set you 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;
})());
精彩评论