我经常创建一个小函数管道。在管道中的某个点,比方说在第 3 级,一个函数可能需要传递一个先前函数不需要的参数。
我可以模拟管道中第一个函数的多次返回,返回一个带有不需要的参数的对象,但我不确定这是一个好的做法。所以我使用 bind 和 this 在我需要的地方专门传递参数:
function errorMessageBag( fields, model ) {
const execution = R.pipe( normalizedFormFields,
mergedModelAndFormFields.bind( this, model ), // Here I pass an argument only needed by this function
fieldsWithValidation,
requiredFields,
stringLengthValidation,
emailValidation,
urlValidation )
return execution( fields ) // Parameter respects signature of first function in the flow.
}
你看到在这个例子中我传递给 mergedModelAndFormFields 一个参数,模型。 工作正常,但这是常见做法还是不良做法?如果不好,处理这个问题的正确方法是什么?
最佳答案
我认为这种方法没有任何问题。
你总是可以定义一个内部函数并在管道中使用它:
function errorMessageBag(fields, model) {
const execution = R.pipe(normalizedFormFields,
mergedModelAndFormFieldsWrapped,
fieldsWithValidation,
requiredFields,
stringLengthValidation,
emailValidation,
urlValidation);
return execution(fields)
function mergedModelAndFormFieldsWrapped(fields) {
// model is accessible here
}
}
关于ramda.js - 使用 bind this 将参数传递到管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38523687/