I'm trying to find a better way to write a piece of jQuery but I couldn't figure it out on my own.
$('.ajaxButton').click(function(event) {
event.preventDefault();
var button = $(this).data('button');
var action = $(this).data('buttonaction');
var target = $(this).data('buttontarget');
// The following code needs a rewrite
if (action === 'fadeIn') {
$(target).fadeIn();
} else if (action === 'slideDown') {
$(target).slideDown();
} else if (action === 'fadeToggle') {
$(target).fadeToggle();
} else if (action === 'slideToggle') {
$(target).slideToggle();
} else {
console.log('Action not found for ' + button + ' button.');
}
});
In order to avoid having to write the same code over and over again, I wrote the above JS for buttons I create in my web application. The above code works with the following anchor:
<a href="#"
class="button ajaxButton"
data-button="showForm"
data-buttonaction="slideToggle"
data-buttontarget=".showForm" >...</a>
What I have been trying to figure out is if there is a better way to write the following piece of code:
if (action === 'fadeIn') {
$(target).fadeIn();
} else if (action === 'slideDown') {
$(target).slideDown();
} else if (action === 'fadeToggle') {
$(target).fadeToggle();
} else if (action === 'slideToggle') {
$(target).slideToggle();
} else {
console.log('Action not found for ' + button + ' button.');
}
I would like to avoid the use of if: else statements. My first instinct was to have some sort of array that contains all possible actions. From there, I conduct a simple if action is in array do....
var actionArray = new Array('fadeIn', 'slideDown'...);
if ($.inArray(action, actionArray)) {
$(target).action();
}
But I have no idea how to create the function. Can I call functions based on array values? Or can I convert strings to functions? I think the closest I could find was to use the eval() function.
Is there a better way to do this? Or will I have to use if else statements?
if ( target[ action ] ) target[ action ]();could work. But no idea how to convert it to jquery. The point is, as long as the action is the same spelling as the method name you are calling, you can use the action string to call the function in bracket notation instead of dot notation. Never useeval()unless you can exactly explain why you are using it. You could also use a switch() statement same way as inside reducers. PS: if you use an actual button instead of a hyperlink you do not have topreventDefault().$(target)[action]()