如何改进这个包含基本重复逻辑的toggleClass函数?

时间:2015-10-20 10:21:02

标签: javascript jquery

我有一个toggleClass函数,它基本上会反转if..else中的类,具体取决于状态是删除还是重置。任何人都可以提出任何关于如何改进它以使其更好的建议吗?

JS

/**
 * Uses the click events currentTarget as the element and a state string
 * to work out how the required classes should be toggled.
 * 
 * @param $el - jQuery click event
 * @param state - string `reset` or `delete`
 */
toggleClass: function($el, state) {

    console.log('toggleClass', state);

    if(state === 'delete') {
        $el.toggleClass('js-delete-session js-reset-session');
        $el.toggleClass('fa-times fa-undo');
    } else {
        $el.toggleClass('js-reset-session js-delete-session');
        $el.toggleClass('fa-undo fa-times');
    }

},

2 个答案:

答案 0 :(得分:4)

当您在两种状态下切换相同的类时,您不需要单独的状态代码。您甚至可以将这些类放在同一个调用中:

toggleClass: function($el) {
  $el.toggleClass('js-delete-session js-reset-session fa-times fa-undo');
},

答案 1 :(得分:2)

切换班级js-delete-sessionjs-reset-session的第一个语句在ifelse块中都很常见,可以移到if else之外。< / p>

toggleClass: function($el, state) {
    // Common to both delete and reset
    $el.toggleClass('js-delete-session js-reset-session');

    if(state === 'delete') {
        $el.toggleClass('fa-times fa-undo');
    } else {
        $el.toggleClass('fa-undo fa-times');
    }
},

此外,三元运算符可用作if...else

的选项
toggleClass: function($el, state) {
    $el.toggleClass('js-delete-session js-reset-session');
    state === 'delete' ? $el.toggleClass('fa-times fa-undo') : $el.toggleClass('fa-undo fa-times');
},

OR,

toggleClass: function($el) {
    $el.toggleClass('js-delete-session js-reset-session fa-times fa-undo');
},