使用bind this将参数传递给管道

时间:2016-07-22 10:06:21

标签: ramda.js

我经常创建一个小函数管道。在管道中的某个点,让我们说在第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一个参数,模型。 工作正常,但这是一种常见做法还是不良做法?如果不好,那么处理这个问题的正确方法是什么?

2 个答案:

答案 0 :(得分:0)

我认为这种方法没有任何问题。

你总是可以定义一个内部函数并在管道中使用它:

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
    }
}

答案 1 :(得分:0)

就像他评论中提到的Scott一样,我只想讨论mergedModelAndFormFields,最好是在管道中使用之前。如果这是你需要咖喱这个功能的唯一地方,你可以这样做,就像这样:

function errorMessageBag( fields, model ) {
    const execution = R.pipe( normalizedFormFields,
                              R.curry(mergedModelAndFormFields)(model),
                              fieldsWithValidation,
                              requiredFields,
                              stringLengthValidation,
                              emailValidation,
                              urlValidation )

    return execution( fields ) // Parameter respects signature of first function in the flow.
}