jQuery: Change plugin option after called
I've a plugin made by my own to set up a few things when using dialog of jquery-ui. Instead of calling:
$("#popup").dialog(options);
I use this:
$("#popup").dialogPlugin(options);
And dialogPlugin will call .dialog(options)
(after doing some stuff).
In my plugin I may modify some functions for the events of the dialog like this:
var originalCloseFn = options.close;
options.close = function() {
//my own stuff.
originalCloseFn();
};
The plugin works great, but after some time using it I realized that I couldn't change the dialog functions from outside the plugin like this:
$("#popup").dialog("option", "close", newFunctionOnClose);
If I do that the code the plugin added to the close function would be lost.
So I added this code at the beggining of my plugin:
if (options == "option") {
if (val == undefined)
return _this.dialog("option", name);
else
return _this.dialog("option", name, val);
}
Now I need to change the fifth line of this code to actually change the option of my plugin, not of the jquery-ui. (The option of .dialogPlugin
function, not of .dialog
). I realy don't know how can I do that. Any ideas please?
Edit
I know that the question is not very clear and my poor english doesn't let me to explain myself any more s开发者_如何转开发o I've made a litle example.
What I want is that in the seventh line (return $(this).dialog("option", name, val);
) instead of modifing that (equivalent to optionsForJQuery.close
) modify options.close
. That way I will avoid loding the plugins behavior.
try this:
HTML:
<div id="popup">I'm a popup</div>
JS:
(function ($) {
$.fn.dialogPlugin = function (options, name, val) {
var
// setter function close
fnClose = null,
// function when close
fnMyClose = function() {
alert("This is plugin's close behavior");
if (fnClose)
fnClose();
};
if (options == "option") {
if (name == "close" && $.isFunction(val)) {
fnClose = val;
val = fnMyClose;
}
}
else {
if (options.close)
fnClose = options.close;
options.close = fnMyClose;
}
return (name)
? $(this).dialog(options, name, val) //if var == 'undefined'is equal to not send parameters
: $(this).dialog(options);
};
})(jQuery);
$("#popup").dialogPlugin({
close: function() {
alert("This is user's first close behavior");
}
});
$("#popup").dialogPlugin("option", "close", function() {
alert("This is user's second close behavior");
});
EDIT
or more simple and elegant:
(function($){
var dialog_close = $.ui.dialog.prototype.close;
$.ui.dialog.prototype.close = function() {
var self = this;
alert("This is plugin's close behavior");
dialog_close.apply(this, arguments);
};
})(jQuery);
精彩评论