I am working on a jQuery plugin and I would like for the user to pass in a method name to be executed after a flag (in the code) is set to true. I already have the flags working as needed, I just need a way to execut开发者_开发百科e the method that is passed. For example:
(function(jQuery){
$.fn.extend({
pluginName: function(options) {
var defaults = {
parameter1: 0,
method: function(){}
}
var options = $.extend(defaults, options);
return this.each(function() {
var opt = options;
var flag = false;
if(opt.parameter1 > 0){
flag = true;
}
if(flag){
//call users method
}
jQuery(this).hide();
});//END return
}//END counter method
});//END extend
})//END function
//Return jQuery object
(jQuery);
The user would call it like this:
$("#divName").pluginName({
parameter1: 1,
method: function(){alert("test");}
});
I haven't tested the code above, it's just an illustration so you can see what I'm trying to accomplish. Thanks in advance!
Since functions are first class objects in JavaScript, you can just use
options.method();
in your plugin to execute the function
There is no difference between a user-supplied method like your example and any other method. Therefore, you can call it the same way you call any other method.
For example:
if (flag)
opt.method();
If the method takes arguments, you can pass them the same way you pass arguments to ordinary methods.
This comment doesn't have to do with the point of your question, but I think it's worth noting to help you learn more about jQuery and JS in general.
Your code currently reads:
(function(jQuery) {
$.fn.extend({
/* ... */
});
})(jQuery);
One of the reasons for creating an anonymous function when using jQuery in this manner is so that you can reference the $
object without conflicts with other Javascript libraries. However, you're accepting parameter with name jQuery
into your anonymous function, and then continue on to call $.fn.extend
instead of jQuery.fn.extend
.
If you're planning to reference the jQuery object as $
in your code, I recommend correcting your parameter name to $
in the anonymous function, i.e.:
(function($) {
$.fn.extend({
/* ... */
});
})(jQuery);
精彩评论