【问题标题】:How to hold an event while invoking the same event如何在调用同一事件时保持事件
【发布时间】:2017-12-12 07:51:40
【问题描述】:

如何保持事件触发的角度。

这个问题与我的另一个问题有关:how to stop array.filter() function

我已经尝试了所有答案。但我对这个答案并不满意。

所以我根据自己的想法做了一些事情。

问题: 我有一个ngmodelchange 事件,用于调用方法。您可以查看我的最新问题,了解为什么要使用 ngModelChange() 事件。无论如何,我也会在这里解释。

我使用 ngModelChange 事件搜索和过滤大量数据。所以问题是当我连续输入字符时,应用程序挂起。

我的建议

所以我建议自己在用户停止输入后使用一些逻辑来调用过滤器函数。但我们不知道用户何时会停止输入。

所以我在下面创建了一个逻辑。

做了什么

(ngModelChange)="clearSearch(gloablFilterValue)"// html side

在.ts端

 clearSearch(newValue: string) {
       this.oldFilterText = newValue;
        if (this.isLooping) {
            return false;
        }  

        for (let i = 0; i > newValue.length + 1; i++) {
            this.isLooping = true;
            if (this.oldFilterText == newValue) {
                this.splitCustomFilter();//filter function
            }
        }

    }

上面的代码不起作用。我刚开始写逻辑。因此,如果有人有任何想法。请和我一起提出实现这一目标的建议和想法。

主要问题

在用户在文本框中输入值之前,我们如何才能停止事件触发?我们如何启动触发用户在文本框中输入值的事件?

**重要提示:我不想使用焦点和模糊事件。因为过滤器应该在用户输入值时起作用。

【问题讨论】:

    标签: javascript arrays angular typescript


    【解决方案1】:

    您要查找的内容称为deboucing节流是一个不错的选择。 RxJS 支持两个运算符,称为debounceTimethrottleTime。下面是一个如何使用它们的简单示例。

    在模板中,侦听输入事件(或其他事件,具体取决于您在用例中侦听的内容)。

    <input type=text (input)="onInput($event.target.value)">
    

    在您的组件代码中,创建一个主题,然后在订阅之前对其使用适当的运算符。

    // create a subject
    private subject = new Subject<string>()
    
    // function to call when event fires
    public onInput(input: string) { this.subject.next(input) }
    
    ngOnInit() {
      // debounce the stream
      this.subject.debounceTime(300).subscribe(inputText => {
         // this is where you can do you .filter
         console.log(inputText)
      })
    }
    

    当然,您可以随意调整300 参数。

    【讨论】:

    • 添加.distinctUntilChanged()也有帮助
    • 我在哪里可以使用Subject?为什么我需要使用它?
    • Subject 是 RxJS 的一部分。将其导入为import {Subject} from 'rxjs/Subject'。您可以在他们的文档中了解更多关于 what is RxJS subject 的信息。
    猜你喜欢
    • 2015-10-18
    • 2021-11-04
    • 2019-07-12
    • 1970-01-01
    • 2022-08-19
    • 2017-05-13
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多