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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With