views:

90

answers:

2

Hi, at the moment I have my jQuery plugin running it's logic in if statments.

For example I have:

(function($) {
    $.fn.myplugin = function(action) {

        if(action == "foo"){

        }

        if(action == "bar"){

        }

        if(action == "grapefruits"){            

        }

    }
})(jQuery);

Is there a better way to go about this?

Also the same with event handlers, can I declare them inside the plugin?

+7  A: 

You can store different functions in an object and use an indexer, like this:

(function($) {
    var methods = {
        foo: function(action) { ... },
        bar: function(action, someParam) { ... },
        grapefruits: function(action, param1, param2) { ... },
        ...
    };

    $.fn.myplugin = function(action) {    
        methods[action].apply(this, arguments);
    }
})(jQuery);
SLaks
Can i wrap a string with `$("....")` and add some functions can manipulate the string?
uzay95
+2  A: 

There's no reason to check the action multiple times, is there? YOu may as well use else if.I don't like the syntax for switch personally, and prefer this style. You can do it like

    if(action == "foo"){
    }
    else if(action == "bar"){
    }
    else if(action == "grapefruits"){            
    }
    else{
    //this is the default/unspecified case
    }

Another option is to store each as a name in an object. This is done in Python a lot too, for instance.

   var plugin_actions={
      'foo':function(){},
      'bar':function(){},
      'grapefruits':function(){}
       }
   plugin_actions[action]();
Alex JL
The second solution loses the `this` context and the parameters. See my answer.
SLaks
Very good point, thanks.
Alex JL