乐趣区

关于typescript:Angular9中节流防抖实际运用RxJS自定义指令

因为咱们产品各种模块下的查问场景十分多,所以节流、防抖显得尤为重要,有共事用原生 js+ 闭包封装过相干函数,然而既然是用 angular+rxjs,为何不必自定义指令呢,更加简洁明了,应用也更加不便,话不多说,上代码:

import {Directive, EventEmitter, HostListener, OnInit, Output, OnDestroy, Input} from '@angular/core';
import {Subject} from 'rxjs/Subject';
import {Subscription} from "rxjs/Subscription";
import {debounceTime} from 'rxjs/operators';

@Directive({selector: '[appDebounceClick]'
})
export class DebounceClickDirective implements OnInit, OnDestroy {@Input() debounceTime = 1000; // 工夫参数,默认 1 秒
    @Output() debounceClick = new EventEmitter();
    private clicks = new Subject<any>();
    private subscription: Subscription;

    constructor() {}

    ngOnInit() {
        this.subscription = this.clicks
            .debounceTime(this.debounceTime) // 防抖
            .subscribe(e => this.debounceClick.emit(e)); // 发射事件
    }

    ngOnDestroy() {this.subscription.unsubscribe(); // 勾销订阅
    }

    // 绑定宿主事件
    @HostListener('click') onclick(event: MouseEvent)
    {
        // 阻止浏览器的默认行为和事件冒泡
        event.preventDefault();
        event.stopPropagation();
        this.clicks.next(event); // 此处产生流
    }
}

具体应用:

<button appDebounceClick (debounceClick)="log($event)" [debounceTime]="300">
 Debounced Click
</button>
退出移动版