如何从这个ajax函数中分解出回调函数?

Moh*_*mad 1 ajax jquery design-patterns

我在jQuery中创建了一个可重用的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)
Run Code Online (Sandbox Code Playgroud)

我应该自己分解ajax函数.但我无法想出一种方法将回调条件分离到它们自己的块/函数中,并传回结果.

有任何想法吗?请记住我是JavaScript和jQuery的新手.

Pab*_*dez 5

像这样有一个"动作"地图,保存动作ID并function执行:

var actions = {

  '4' : function () {
    $('.fav-count').text(response.newcount);
    $('.fav-count').toggleClass('on');
  },

  '2' : function() {
    link.siblings('.liked').removeClass('on');
    link.siblings('.count').text(response.newcount);
  }
}
Run Code Online (Sandbox Code Playgroud)

然后在success回调你只是做:

if (response.success) {
   actions[actionTypeId]();
}
Run Code Online (Sandbox Code Playgroud)

请注意,你可能不得不改变一些事情,因为link从回调actions[actionTypeId](this);中看不到,但你可以做类似的事情,然后让回调接收链接作为参数.