Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
381 views
in Technique[技术] by (71.8m points)

angular - Angular 2-取消keyUp事件(Angular 2 - Debouncing a keyUp event)

How can I debounce a function which gets called on an "keyUp" event?

(如何对在“ keyUp”事件上调用的函数进行反跳操作?)

Here is my code:

(这是我的代码:)

My Function

(我的功能)

private handleSearch(searchTextValue: string, skip?: number): void {
    this.searchTextValue = searchTextValue;
    if (this.skip === 0 || typeof skip === "undefined") {
        this.skip = 0;
        this.pageIndex = 1;
    } else {
        this.skip = skip;
    }
    this.searchTextChanged.emit({ searchTextValue: searchTextValue, skip: this.skip, take: this.itemsPerPage });
}

My HTML

(我的HTML)

<input type="text" class="form-control" placeholder="{{ 'searchquery' | translate }}" id="searchText" #searchText (keyup)="handleSearch(searchText.value)">

Bassically what I'm trying to achieve is that handleSearch gets called a few moments after the user stop typing.

(基本上,我想要实现的是在用户停止键入后不久, handleSearch被调用。)

I found out i can use lodash's _debounce() for this, but I haven't found out how to put this on my keyUp event.

(我发现我可以为此使用lodash的_debounce() ,但是我还没有找到如何将其放在我的keyUp事件中。)

  ask by Nicolas translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

UPDATE: Using RXJS 6 pipe operator:

(更新:使用RXJS 6管道运算符:)

this.subject.pipe(
  debounceTime(500)
).subscribe(searchTextValue => {
  this.handleSearch(searchTextValue);
});

You could create a rxjs/Subject and call .next() on keyup and subscribe to it with your desired debounceTime.

(您可以创建一个rxjs / Subject并在keyup上调用.next()并使用所需的debounceTime进行订阅。)

I'm not sure if it is the right way to do it but it works.

(我不确定这是否是正确的方法,但是可以。)

private subject: Subject<string> = new Subject();

ngOnInit() {
  this.subject.debounceTime(500).subscribe(searchTextValue => {
    this.handleSearch(searchTextValue);
  });
}

onKeyUp(searchTextValue: string){
  this.subject.next(searchTextValue);
}

HTML:

(HTML:)

<input (keyup)="onKeyUp(searchText.value)">

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...