【问题标题】:How to handle different logic in an if block with out duplicating code?如何在不重复代码的情况下处理 if 块中的不同逻辑?
【发布时间】:2022-01-13 14:08:41
【问题描述】:

处理执行某些操作但条件不同的 if 块的最佳方法是什么?

假设我在 JavaScript 中有这个函数。

const updateText1 = function (id) {
    const selector = $(id);
    selector.on('change', function () {
        const text = selector.val();
        if(seen[text]) {
            // update some fields here
        } else {
            //more stuff here
        }
    })
}

但是我需要在 if 语句中做同样的事情,但使用不同或相似的条件

const updateText2 = function (id) {
    const selector = $(id);
    selector.on('change', function () {
        const text = selector.val();
        if(seen[text] || text.trim() === '') {
            // update some fields here
        } else {
            //more stuff here
        }
    })
}

那么else函数就是这样使用的

obj1 = {
  test: function() { updateText1(this.id) }
}

obj2 = {
  test: function() { updateText2(this.id) }
}

我知道我可以将逻辑组合在一起,但是,由于这个函数所附加的两个对象处理的事情略有不同,我试图让我的代码保持干燥,而不是多次重复 if 主体。我试过注入这样的逻辑

obj2 = {
  // logic code here
  test: function() { updateText2(this.id, logic) }
}

但这会导致代码不更新,因为值是通过 jQuery on change 获取的。

我是不是想太多了,我应该只是结合逻辑,还是有更好的方法来组织和处理这个?

【问题讨论】:

  • function (id, checkBlank=false) 及更高版本,if(seen[text] || (checkBlank && text.trim() === '')) ...

标签: javascript oop design-patterns functional-programming


【解决方案1】:

最简单的解决方案是传递回调,这可能就是您想要做的。

例子:

const updateText = function (id, predicate) {
    const selector = $(id);
    selector.on('change', function () {
        const text = selector.val();
        if(predicate(text)) {
            // update some fields here
        } else {
            //more stuff here
        }
    })
}

然后可以通过以下方式调用

function canUpdate1(text) {
  return seen[text];
}

function canUpdate2(text) {
  return seen[text] || text.trim() === '';
}

updateText('id1', canUpdate1);
updateText('id2', canUpdate2);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多