我可以重构if - else在javascript中使用switch或case语句吗?

时间:2012-08-19 10:40:25

标签: javascript jquery

我有以下代码:

var btns1 = {
    'Submit': function (win) {
        submitHandler(oLink.$link, $('#main-form'), false);
    },
    'Submit & Close': function (win) {
        submitHandler(oLink.$link, $('#main-form'), true);
    },
    'Close': function (win) {
        modal.closeModal()
    }
}
var btns2 = {
    'Submit & Close': function (win) {
        submitHandler(oLink.$link, $('#main-form'), true);
    },
    'Close': function (win) {
        modal.closeModal()
    }
}

if (oLink.title.substr(0, 4) == "Crea") {
    if (content.match(/data-RowKey="(.{3}).*/)) {
        oLink.title += " " + content.match(/data-RowKey="(.{3}).*/)[1]
    }
    var btns = btns1;
}
if (oLink.title.substr(0, 4) == "Edit") {
    var btns = btns1;
}
if (oLink.title.substr(0, 4) == "Dele") {
    var btns = btns2;
}

有没有办法可以重构代码。我想的是把它放到一个名为“adminModalBtns”的函数中,让它将oLink和content作为参数并让它返回btns。用if-else或case语句做这件事最明显吗?

3 个答案:

答案 0 :(得分:1)

function getButtons(oLink, content) {

    var btns1 = {
        'Submit': function(win) {
            submitHandler(oLink.$link, $('#main-form'), false);
        }
    }
    var btns2 = {
        'Submit & Close': function(win) {
            submitHandler(oLink.$link, $('#main-form'), true);
        },
        'Close': function(win) {
            modal.closeModal()
        }
    }
    switch (oLink.title.substr(0, 4)) {
    case "Crea":
        if (content.match(/data-RowKey="(.{3}).*/)) {
            oLink.title += " " + content.match(/data-RowKey="(.{3}).*/)[1]
        }
    case "Edit":
        return $.extend(btns1, btns2);
    case "Dele":
        return btns2;
    }
}

var btns = getButtons(oLink, content);

答案 1 :(得分:1)

或者您可以使用ternary operators

var sub = oLink.title.substr(0, 4)
   ,bttns =  sub === "Crea" ? btns1 
           : sub === "Edit" ? btns1 
           : btns2;
oLink.title += /data-RowKey="(.{3}).*/.test(content) 
               ? ' ' + content.match(/data-RowKey="(.{3}).*/)[1] 
               : ''; 

答案 2 :(得分:0)

您还可以使用哈希映射conditionMap重构代码,并创建变量re来存储正则表达式/data-RowKey="(.{3}).*/

var getButtons = function (oLink, content) {
        var re = new RegExp(/data-RowKey="(.{3}).*/),
            btns1 = {
                'Submit': function (win) {
                    submitHandler(oLink.$link, $('#main-form'), false);
                }
            },
            btns2 = {
                'Submit & Close': function (win) {
                    submitHandler(oLink.$link, $('#main-form'), true);
                },
                'Close': function (win) {
                    modal.closeModal();
                }
            },
            conditionMap = {
                'Crea': (content.match(re)) && (oLink.title += ' ' + content.match(re)[1]),
                'Edit': $.extend(btns1, btns2),
                'Dele': btns2
            };

        return conditionMap[oLink.title.substr(0, 4)];
    },
    btns = getButtons(oLink, content);