Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a better jQuery plugin

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?

like image 467
MintDeparture Avatar asked Feb 28 '10 18:02

MintDeparture


1 Answers

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);
like image 113
SLaks Avatar answered Oct 14 '22 08:10

SLaks