javascript - 为什么我们使用两个过滤器?

标签 javascript rxjs rxjs6

为什么我们在下面的代码中使用两个过滤器而不是一个?

 fromEvent<MouseEvent>(this.mapElement, "click")
    .pipe(
        filter(e => !this.props.disableEvents),
        filter(_ => !this.mouseState.moved && mouseDownInMap)
    )
    .subscribe(e => {});

为什么不:
fromEvent<MouseEvent>(this.mapElement, "click")
    .pipe(filter( e => !this.props.disableEvents && !this.mouseState.moved && mouseDownInMap))
    .subscribe(e => {});

另外,为什么我们需要 .pipe()如果它也可以在没有管道的情况下工作?

最佳答案

您可以将它们组合成一个 filter .

但是为了代码维护,通常更容易阅读两个单独的过滤器函数,特别是如果它们在概念上不相关 - 并避免水平滚动。

另一个原因是过滤器函数本身可能在别处定义,在这种情况下,您必须使用单独的 filter无论如何调用:

例如

function whenEventsAreEnabled( e ) {
    return !this.props.disableEvents;
}

function whenMouseIsInMap( e ) {
    !this.mouseState.moved && mouseDownInMap
}

fromEvent<MouseEvent>(this.mapElement, "click")
    .pipe(
        filter( whenEventsAreEnabled ),
        filter( whenMouseIsInMap )
    )
    .subscribe(e => {});

Also, why we need .pipe() if it works without pipe too?



需要pipe .您只能在不使用 pipe 的情况下逃脱。如果你在 backwards compatibility mode 中使用 RxJS . Modern RxJS always requires pipe() to create a pipeline for the observable's emitted values/objects .

关于javascript - 为什么我们使用两个过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60504849/

相关文章:

typescript - 使用 SubSink 而不是 Subscriptions 数组有什么意义

javascript - 如何在 Winstonjs 记录器中记录未处理的超时错误?

javascript - 使用 firebase 和 vuejs 过滤数组

javascript - 如何在 javascript 中找到我刚刚单击的行

javascript - 声明全局更新窗口不起作用

javascript - Angular 4 - 可观察订阅中对 'this' 的引用似乎引用了旧数据

javascript - 在 Angular 中链接可观察订阅的最佳方式?

angularjs - ReactiveX JS 和 TypeScript - 如何退订?

angular - rxjs , switchMap ,间隔,提供了 'undefined',其中需要一个流

javascript - 延迟 n 秒重试轮询服务