1

我有以下代码:

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 语句来做这件事最清楚吗?

4

3 回答 3

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);
于 2012-08-19T11:14:59.163 回答
1

或者,您可以使用三元运算符

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] 
               : ''; 
于 2012-08-19T11:36:30.530 回答
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);
于 2016-12-10T22:32:26.507 回答