我在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