angular4 防二次重複點擊

監聽click事件,
默認三秒鐘內的點擊事件觸發第一次的點擊事件,也能夠經過throttleTime自定義時間 只觸發第一次app

/**
 * <div  (throttleClick)="goExceptionReport()" [throttleTime]="5000">throttleClick 5 S</div>
 * <div  (throttleClick)="goExceptionReport()">throttleClick default</div>
 * <div tappable (throttleClick)="goExceptionReport()">throttleClick default with tappable</div>
 */
import { Directive, EventEmitter, HostListener, Input, OnDestroy, OnInit, Output } from "@angular/core";
import { Subject } from "rxjs/Subject";
import { Subscription } from "rxjs/Subscription";

@Directive( {
  selector: "[throttleClick]",
} )
export class ThrottleClickDirective implements OnInit, OnDestroy {
  @Input() public throttleTime = 3000;
  @Output() public throttleClick = new EventEmitter();
  private clicks = new Subject<any>();
  private subscription: Subscription;

  constructor() {}

  ngOnInit() {
    // 攔截點擊事件只傳遞第一次點擊事件的處理操做交給parent來處理
    this.subscription = this.clicks
      .throttleTime( this.throttleTime )
      .subscribe(( e ) => this.throttleClick.emit( e ) );
  }

  ngOnDestroy() {
    // 取消訂閱
    this.subscription.unsubscribe();
  }

  // HostListener這個裝飾器能夠監聽directive做用的dom元素的click事件,第二個參數$event告訴Angular傳遞點擊事件到directive中去;
  @HostListener( "click", [ "$event" ] )
  clickEvent( event: MouseEvent ) {
    // 防止事件繼續向parent component中傳遞
    event.preventDefault();
    event.stopPropagation();
    // 這裏使用subject的.next來傳遞點擊事件,而後使用rxjs的函數操做符throttleTime來處理延時事件,在指定事件內只處理第一次操做,調用emit傳遞點擊事件的操做到parent中去繼續處理;
    this.clicks.next( event );
  }
}

默認三秒鐘內的點擊事件觸發最後一次的點擊事件,也能夠經過debounceTime自定義時間 只觸發最後一次dom

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

    @Directive({  
        selector: '[appDebounceClick]'  
    })  
    export class DebounceClickDirective implements OnInit {  
        @Input() debounceTime = 500;  
        @Output() debounceClick = new EventEmitter();  
        private clicks = new Subject();  
        private subscription: Subscription;  

        constructor() { }  

        ngOnInit() {  
            // 攔截點擊事件而後延遲這些點擊事件的執行,直到一段時間內最後一次點擊,最後把事件的處理操做交給parent來處理
            this.subscription = this.clicks.pipe(  
                debounceTime(this.debounceTime)  
            ).subscribe(e => this.debounceClick.emit(e));  
        }  

        ngOnDestroy() {  
            this.subscription.unsubscribe();  
        }  

        @HostListener('click', ['$event'])  
        clickEvent(event) {  
            event.preventDefault();  
            event.stopPropagation();  
            this.clicks.next(event);  
        }  
    }
相關文章
相關標籤/搜索