简体   繁体   English

如何在“链接的”方法调用中使用条件语句?

[英]How to have conditional statements in “linked” method calls?

Is there a cleaner way of writing this code? 有没有更干净的方式编写此代码? It's only the .trim() statement that differs. 只是.trim()语句有所不同。

if (imageOptions.trim) {
    // Trim
    gm(imageBuffer, 'image.' + imageOptions.imageFormat)
        .gravity(imageOptions.gravity)
        .resize(imageOptions.imageWidth, imageOptions.imageHeight, '^')
        .crop(imageOptions.imageWidth, imageOptions.imageHeight)
        .trim()
        .toBuffer(imageOptions.imageFormat.toUpperCase(), callback);
}
else {
    // No trim
    gm(imageBuffer, 'image.' + imageOptions.imageFormat)
        .gravity(imageOptions.gravity)
        .resize(imageOptions.imageWidth, imageOptions.imageHeight, '^')
        .crop(imageOptions.imageWidth, imageOptions.imageHeight)
        .toBuffer(imageOptions.imageFormat.toUpperCase(), callback);
}

Bonus question: what's the proper terminology for these "linked" method calls? 额外的问题:这些“链接”方法调用的正确术语是什么?

You can assign the result of those method calls to a variable and then have a conditional, there's no need to write the entire chain unbroken: 您可以将这些方法调用的结果分配给变量,然后有条件,无需完整地编写整个链:

var img = gm(...)
            .gravity(..)
            .resize(..)
            .crop(..);

if (imageOptions.trim) {
    img.trim();
}

img.toBuffer(..);

And these things are called chained method calls . 这些事情称为链接方法调用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM