I created a reusable ajax pattern in jQuery. It works well, but it’s starting to become messy as I add more actions to it.
Look at the success callback. Every time I add a new action, the conditional logic gets messier: if actionType == foo, then bar etc…
$('.action-panel').delegate('a', 'click', function () {
var link = $(this),
actionTypeId = link.data('action-type-id'),
// Do stuff, like getting the url from the link, etc...
// Throttle multiple clicks
$.ajax({ //[snip]
beforeSend: function () {
link.toggleClass('on');
},
error: function () {
link.toggleClass('on');
},
success: function (response) {
if (response.success) {
if (actionTypeId === 4) {
// do stuff for action 4
}
else if (actionTypeId === 2) {
// do stuff related to action 2
}
else if (actionTypeId === 3) {
// do stuff related to action 3
}
// More action types, etc...
}
else {
link.toggleClass('on');
}
// decide to show tooltip or not
});
// do some extra stuff like re-enable the link (throtled earlier)
I should factor out the ajax function by itself. But I can’t figure out a way to separate the callback conditionals into their own blocks/functions, and pass back the result.
Any ideas? Please bare in mind I’m new to JavaScript and jQuery.
Have an “action” map like this, saving the action ID and the
functionto execute:Then on the
successcallback you just do:Note you’ll probably have to change a bit things since
linkwont be visible from the callback but you can do something likeactions[actionTypeId](this);and then have the callbacks receive the link as a parameter.