# Change functions based on jQuery plugin {options}

I'm developing my first legitimate jQuery plugin, and I'm trying to keep it very modular. To do this, I'm writing many individual functions, which is fine, but I need a clean way to determine what functions to fire based on the plugin options provided by the user.

Right now, I'm using a .on('click',...) event with a switch statement. That method is ok and I just have a feeling that there is a better, time-tested method of changing what function is fired based on plugin {options}. A better method that is used by professional JavaScript developers and has been proven to work reliably.

Again, I'm trying to be as modular and professional as possible, but I'm self taught, so there's really no one to say if I'm doing it the "right" way, or the "best" way for future maintainability.

JSFiddle

(function($){$.fn.showDateTime = function(options) {

// variables and settings
var d;
var $button =$(this);
var defaults = {
date: "all"
};
var settings = $.extend({}, defaults, options); // event handlers$button.on('click', function(){
d = new Date();
switch(settings.date){
case "all": showDate();
break;
case "date only": showDateOnly();
break;
case "time only": showTimeOnly();
break;
default: showDate();
}
});

// functions
function showDate(){
}
function showDateOnly(){
}
function showTimeOnly(){
}
};
})(jQuery);

\$('#button').showDateTime({date:"date only"});

• @Jamal... yikes! XD Thanks for your edits. After more trials the method I eventually settled on and was happy with was along these lines. Seems cleaner and easily maintainable. jsfiddle.net/49swq015 – TJBlackman Nov 28 '16 at 5:11

In my opinion it's a good idea to get rid of the switch case by using better naming for the inputs and by changing the structure of your functions to Object based functions, i.e. if you change your functions to this:

var showDate={
all:function (){
},
date:function showDateOnly(){
},
time:function (){
}
};


and the setting options you get are ['all' , 'date' , 'time']

then you can call these functions like this:

(showDate[settings.date]) ? showDate[settings.date]() : showDate.all();


and get rid of the switch case. DEMO

• This is a good suggestion! I will keep this style of coding in mind as a continue. – TJBlackman Dec 1 '16 at 5:00