如何重构If-else代码段?

时间:2012-12-11 13:24:30

标签: javascript microsoft-metro

我正在使用Html5-js-jquery开发win8(metro风格)应用程序。 我有这段代码;

    GetBoutiqueDetail: function (boutiqueId, options) {
        if (IsUserLogin()) {
            //different job A
        } else {
            ShowLoginPanel(undefined);
        }
    },
    GetProductDetail: function (boutiqueId, productId, options) {
        if (IsUserLogin()) {
            //different job B
        } else {
            ShowLoginPanel(undefined);
        }
    },
    AddBasket: function (productId, productVariantId, quantity, options) {
        if (IsUserLogin()) {
            //different job C
        } else {
            ShowLoginPanel(undefined);
        }
    },....

。大约20个函数应检查用户是否登录。 我应该调用类似“ Library.GetBoutiqueDetail(); ”的函数

所以我的问题很简单,如何重构该代码以删除这些if-else部分?

5 个答案:

答案 0 :(得分:2)

对象图如何:

var objMap = {  
  "GetBoutiqueDetail":fnJobA,
  "GetProductDetail":fnJobB,
  "AddBasket":fnJobC}
  ....
}

if (loggedIn) {
  objMap[task]();
}
else {
  doLogin();
}

答案 1 :(得分:2)

尝试这样的事情:

checkLogin: function( action, actionArgs ) {

    if( IsLogin ) {

        return action.apply(this, actionArgs );
    }

    ShowLoginPanel();
},

GetBoutiqueDetail: function (boutiqueId, options) {

    //different job A
},
GetProductDetail: function (boutiqueId, productId, options) {

    //different job B
},
AddBasket: function (productId, productVariantId, quantity, options) {

    //different job C
}

答案 2 :(得分:1)

在Javascript中,您可以从函数返回以结束它,所以f.ex:

GetProductDetail: function (boutiqueId, productId, options) {
    if (!IsLogin) return ShowLoginPanel();
    // different job...
}

你仍然会有一些重复的代码。另一种选择是定义更高级别的功能。类似的东西:

var loginOrAction = function() {
    if (!IsLogin) return ShowLoginPanel();
    var args = [].slice.call(arguments);
    Library[args.shift()].apply(Library, args);
}

loginOrAction('GetBoutiqueDetail', boutiqueId, options);

答案 3 :(得分:1)

您总是可以将公共代码包装到更高范围的函数中,并从库函数中调用它 - 例如:

//Higher scope:
function CheckForLogin(executionFunction)
{
   if(IsLogin) {
      executionFunction();
   } else {
      ShowLoginPanel(undefined);
   }
};


GetBoutiqueDetail: function (boutiqueId, options) {
    CheckForLogin(//different job A)
}

different job 'N'作为匿名函数传递给CheckForLogin

答案 4 :(得分:-2)

使用三元运算符

(IsLogin) ? jobA() : ShowLoginPanel(undefined)
相关问题