views:

64

answers:

3

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 execute 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 advanced!

+4  A: 

Since functions are first class objects in JavaScript, you can just use

options.method();

in your plugin to execute the function

Russ Cam
+1  A: 

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.

SLaks
+1  A: 

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);
Matt Huggins
take a look at the comments on the question :)
Russ Cam
Thanks for pointing that out. I intended on using the jQuery namespace to avoid conflicts with other libraries; I forgot to replace all "$" with "jQuery".
qwertypants