0

have the following function on my collection:

getFiltered: function (status, city) {
        return this.filter(function (trainer) {
            return ((status === null) ? trainer : trainer.get("TrainerStatusName") === status) &&
                    ((city === null) ? trainer : trainer.get('City') === city);
        });
    }

What is is best way to deal with nullable params passed in i.e. if city it null then ignore filter/fetch all and if status is null then ignore filter/fetch all

The code above works, but curious about alternatives

4

1 回答 1

0

好的,首先,我对你的问题有点困惑;标题说它是关于处理“可空”参数的,但是您的代码看起来像是在处理“特殊情况”参数(特别是“全部”)......除了培训师为空的情况,但我不认为甚至在遍历 Backbone 集合时也是可能的。

* * 编辑 * * OP 更新了问题,因此上述内容不再相关。我也相应地更新了我的答案。

在任何情况下,您的代码都没有任何错误或不寻常之处。三元运算符是处理一次性特殊情况的标准方法。但是,如果您正在寻找替代想法,这里有一个使用额外功能来干燥(消除重复)您的代码的想法:

function matchesOrAll(expected, actual) {
    return expected === null || expected === actual;
}

getFiltered: function (status, city) {
    return this.filter(function (trainer) {
        return matchesOrAll(status, trainer.get("TrainerStatusName") &&
               matchesOrAll(city, trainer.get("City"));
}

* * 编辑 * *

既然我们谈论的是空值而不是“全部”,值得指出的是,对于更简单的空值/未定义情况,有一个更好的模式。例如,如果您只是过滤城市,则代码可能只是:

getFiltered: function (expectedCity) {
    return this.filter(function (currentCity) {
        return expectedCity === (currentCity || expectedCity);
}

换句话说,您可以利用 Javascript 的“真实性”,以及析取(即||)布尔表达式返回第一个真实值的事实。这消除了对三元组的需要,许多库使用这种模式来填充未提供的参数;例如,下面是 jQuery 中的一行,如果没有提供,则将“target”参数设置为新对象:

target = arguments[1] || {};

不幸的是,当您处理事物的属性/属性(例如trainer.get('foo'))而不是直接处理对象(例如trainer)时,没有什么好的捷径可以使用(除了创建一个函数)。

于 2012-07-01T18:21:38.460 回答