如何消除内部组件的@Output的反跳? [英] how do I debounce the @Output of an inner component?
问题描述
我有一个包装另一个组件<inner-component>
并绑定到InnerComponent.innerChanged()
自定义事件的组件.我想使用@output
属性来冒泡,但我也想对输出进行去抖动.
I have a component that wraps another component <inner-component>
and binds to the InnerComponent.innerChanged()
custom event. I want to bubble up using an @output
property, but I also want to debounce the output.
如何使用RxJS
.debounce()
或.debounceTime()
来做到这一点?
How do I use RxJS
.debounce()
or .debounceTime()
to do this?
类似这样的东西:
import {Component, Output, EventEmitter} from 'angular2/core';
import 'rxjs/add/operator/debounce';
import 'rxjs/add/operator/debounceTime';
@Component({
selector: 'debounced-component',
template: `
<div>
<h1>Debounced Outer Component</h1>
// export class InnerComponent{
// @Output() innerChanged: new EventEmitter<string>();
// onKeyUp(value){
// this.innerChanged.emit(value);
// }
// }
<input #inner type="text" (innerChange)="onInnerChange(inner.value)">
</div>
`
})
export class DebouncedComponent {
@Output() outerValueChanged: new EventEmitter<string>();
constructor() {}
onInnerChange(value) {
this.outerValuedChanged.emit(value); // I want to debounce() this.
}
}
推荐答案
要去抖动值,可以使用主题".主题既是可观察的,又是观察者.这意味着您可以将其视为可观察的对象,也可以将值传递给它.
To debounce values you could use a Subject. A subject is both an observable and a observer. This means you can treat it as an observable and pass values to it as well.
您可以利用它来将新值从内部组件传递给它,然后以这种方式对其进行去抖动.
You could leverage this to pass the new values from the inner-component to it and debounce it this way.
export class DebouncedComponent {
@Output() outerValueChanged: new EventEmitter<string>();
const debouncer: Subject<string> = new Subject<string>();
constructor() {
// you listen to values here which are debounced
// on every value, you call the outer component
debouncer
.debounceTime(100)
.subscribe((value) => this.outerValuedChanged.emit(value));
}
onInnerChange(value) {
// send every value from the inner to the subject
debouncer.next(value);
}
}
这是未经测试的伪代码.您可以在此处看到该概念的有效示例( http://jsbin.com/bexiqeq/15/edit?js,console ).它没有角度,但是概念保持不变.
This is untested pseudo-code. You can see a working example of the concept here (http://jsbin.com/bexiqeq/15/edit?js,console). It's without angular but the concept remains the same.
更新:对于较新版本的Angular,您可能需要稍作改动:将debouncer.debounceTime(100)
更改为debouncer.pipe(debounceTime(100))
Update: For newer versions of Angular you might need a slight: change debouncer.debounceTime(100)
gets changed to debouncer.pipe(debounceTime(100))
constructor() {
// you listen to values here which are debounced
// on every value, you call the outer component
debouncer
.pipe(debounceTime(100))
.subscribe((value) => this.outerValuedChanged.emit(value));
}
这篇关于如何消除内部组件的@Output的反跳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!