1

因为我们产品各种模块下的查询场景非常多,所以节流、防抖显得尤为重要,有同事用原生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>

星不克
52 声望2 粉丝

一蓑烟雨任平生