【问题标题】:using bind this to pass argument down the pipe使用 bind this 将参数向下传递
【发布时间】:2017-09-02 01:22:19
【问题描述】:

我经常创建一个包含小函数的管道。在管道中的某个时刻,假设在第 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.
}

您在这个示例中看到我将一个参数模型传递给 mergeModelAndFormFields。 工作正常,但这是一种常见的做法还是不好的做法?如果不好,处理这个问题的正确方法是什么?

【问题讨论】:

  • 你的方法在我看来是合理的。
  • 如果你不需要在调用中访问this,那么柯里化函数可能是一个更干净的选择。但如果你这样做,这似乎很好。
  • 谢谢大家,复制这些作为答案,我会选择它。

标签: ramda.js


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    就像Scott 在他的评论中提到的那样,我只会咖喱合并的ModelAndFormFields,最好是在管道中使用之前。如果这是您唯一需要 curry 该函数的地方,您可以就地执行,如下所示:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-24
      • 1970-01-01
      • 2019-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多