[英]How to handle different logic in an if block with out duplicating code?
處理執行某些操作但條件不同的 if 塊的最佳方法是什么?
假設我在 JavaScript 中有這個 function。
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
}
})
}
然后像這樣使用其他函數
obj1 = {
test: function() { updateText1(this.id) }
}
obj2 = {
test: function() { updateText2(this.id) }
}
我知道我可以將邏輯組合在一起,但是,由於這個 function 所附加的兩個對象處理的事情略有不同,我試圖保持我的代碼干燥,而不是多次重復 if 主體。 我試過注入這樣的邏輯
obj2 = {
// logic code here
test: function() { updateText2(this.id, logic) }
}
但這會導致代碼不更新,因為該值是通過 jQuery 在更改時獲得的。
我是不是想太多了,我應該結合邏輯,還是有更好的方法來組織和處理這個?
IMO 最簡單的解決方案是傳遞回調,這可能就是您想要做的。
例子:
const updateText = function (id, conditionCallback) {
const selector = $(id);
selector.on('change', function () {
const text = selector.val();
if(conditionCallback(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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.