我在jQuery中创建了一个可重用的ajax模式。它运作良好,但随着我添加更多操作,它开始变得混乱。如何从这个ajax函数中分解出回调函数?
看看success
的回调。我每次添加一个新的动作,条件逻辑混乱得到:if actionType == foo, then bar
等等
$('.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)
我应该自行分解出的AJAX功能。但我无法想出一种方法将回调条件分离到自己的块/函数中,并将结果传回。
任何想法?请记住我是JavaScript和jQuery的新手。
我建议使用名称(而不是数字)标识函数,并将链接和响应传递给回调,以便您可以使用它们。就像:http://jsfiddle.net/Lobstrosity/kQtTV/ – Lobstrosity
确实,我在想同样的事情,但它会让答案更长,可能只是一件好事。我们甚至不知道问题的代码是真实的还是仅仅是一个例子 –
@Lobstrosity和Pablo,谢谢你们。我想我可以将标记更改为''谢谢。 – Mohamad