基于参数存在的条件混合 [英] Conditional mixin based on parameter existence

查看:79
本文介绍了基于参数存在的条件混合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何建议如何基于参数存在来创建条件mixin? 例如,我需要验证是否已传递所有参数才能执行某些操作,例如:

Any suggestion how to create a conditional mixin based on parameter existence? For example I need to to verify that all the parameters are passed in order to perform something or not, for example:

.margin (@margintop:0,@marginbottom:0,@marginright:0,@marginleft:0) {

  // if @marginright:0 or @marginleft:0 are passed do that...

  // else...

}

推荐答案

1:

通常,当您需要为传递的不同数量的参数生成不同的事物时,根本不需要使用默认参数值,例如:

1:

In general, when you need to generate different things for different number of arguments passed you don't need to use default argument values at all, e.g.:

.margin(@top, @bottom, @right, @left) {
    /* right and left are passed */
}

.margin(@top, @bottom) {
    /* right and left are not passed */
}

.margin() {
    /* no arguments passed */
}

// etc.

请注意,这些混合中的每一个都可以复用其他混合,例如,.margin(@top, @bottom)可以对无大小写情况"做一些特殊的事情,然后调用.margin(@top, @bottom, 0, 0)来执行主要工作.

Note that each of these mixins can reuse the others, for example .margin(@top, @bottom) can do something special for the "no right and left case" and then call .margin(@top, @bottom, 0, 0) to perform the main job.

但是,如果由于某些原因您仍然需要这些默认值,则可以使用一些不能作为有效边距的特殊默认值,例如像这样的东西:

But if you still need these defaults for some reason you can use some special default value that can't be a valid margin, e.g. something like this:

.margin(@top: undefined, @bottom: undefined, @right: undefined, @left: undefined) {
    .test-args();

    .test-args() when (@right = undefined) {
        /* right is not passed */
    }
    .test-args() when (@left = undefined) {
        /* left is not passed */
    }

    .test-args()
        when not(@right = undefined)
        and  not(@left  = undefined) {
            /* right and left are passed */
    }

    // etc.
}

3:

第三个选择是使用可变参数并测试其数量,但这是我认为最冗长和愚蠢的:

3:

And the third option would be to use variadic arguments and test their count, but this one is the most verbose and dumb I guess:

.margin(@args...) {
    .eval-args(length(@args));  // requires LESS 1.5.+
    .eval-args(@nargs) {
        // default values:
        @top:    not passed;
        @bottom: not passed;
        @right:  not passed;
        @left:   not passed;
    }
    .eval-args(@nargs) when (@nargs > 0) {
        @top:    extract(@args, 1);
    }
    .eval-args(@nargs) when (@nargs > 1) {
        @bottom: extract(@args, 2);
    }
    .eval-args(@nargs) when (@nargs > 2) {
        @right:  extract(@args, 3);
    }
    .eval-args(@nargs) when (@nargs > 3) {
        @left:   extract(@args, 4);
    }

    args: @top, @bottom, @right, @left;
}

尽管在某些特殊用例中它可能有其优点.

Though it may probably have its pros in some special use-cases.

这篇关于基于参数存在的条件混合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆