2017-03-23 19 views
0

をクリックイベントを防ぐ:は、私は、次のangular2テンプレートが長押しで

<div (click)="foo()"> 
    <img (longPress)="bar(1)" (click)="foobar(1)" /> 
    <img (longPress)="bar(2)" (click)="foobar(2)"/> 
</div> 

Longpressは、あなたが500ミリ秒のためのマウスダウンを持っていたときにトリガーするカスタム属性ディレクティブです。

クリックイベントは、<div>および<img>で処理されます。画像上に長押しをすると、bar()関数が呼び出されます。ただし、mouseUp(長押し後)では、クリックイベントは<img>および親<div>でトリガーされます。

これらのクリックイベントを最も簡単な方法で防止するにはどうすればよいですか。

ここで私が考えることのできるのは、500ミリ秒未満の「クリック」だけをトリガーするカスタム属性指示文を書くことです。これはちょうど私の上に少し上のようです。

答えて

0

は、私が "longPress" と "shortPress" ディレクティブを作成することになりました。 ロングプレスは、設定された時間が経過した後にのみ起動し、ショートプレースは同じしきい値を下回ります。

import { Directive, HostListener, Output, EventEmitter } from '@angular/core'; 

@Directive({ selector: '[shortPress]' }) 

export class ShortPressDirective { 

    @Output() 
    shortPress = new EventEmitter(); 

    private _timeout: any; 
    private _isShort: boolean; 

    @HostListener('mousedown') onMouseDown(e) { 
     this._isShort = true; 
     this._timeout = setTimeout(() => { 
      this._isShort = false; 
     }, 500); 
    } 

    @HostListener('mouseup') onMouseLeave(e) { 
     if (this._isShort) { 
      this.shortPress.emit(e); 
     } 
     clearTimeout(this._timeout); 
    } 

    @HostListener('mouseleave') onMouseUp() { 
     clearTimeout(this._timeout); 
    } 
} 

import { Directive, HostListener, Output, EventEmitter } from '@angular/core'; 

@Directive({ selector: '[longPress]' }) 

export class LongPressDirective { 

    @Output() 
    longPress = new EventEmitter(); 

    private _timeout: any; 

    @HostListener('mousedown') onMouseDown(e) { 
     this._timeout = setTimeout(() => { 
      this.longPress.emit(e); 
     }, 500); 
    } 

    @HostListener('mouseup') onMouseLeave() { 
     clearTimeout(this._timeout); 
    } 

    @HostListener('mouseleave') onMouseUp() { 
     clearTimeout(this._timeout); 
    } 
} 
0

$eventを最初のパラメータとして渡してみましたが、bar()メソッドでevent.stopPropagation()を実行しましたか?このような 何か:

<img (longPress)="bar($event,1)" (click)="foobar(1)" />

function bar(event:Event,myNum:number){event.stopPropagation();}

+0

私はそのような構造のものだと思いましたが、それは私が呼び出される関数を変更する必要が意味するであろう。私はむしろ、属性ディレクティブ自体の解決策を持っているので、機能するために渡された関数の特定のフォーマットは必要ありません。 さらに、longpressはmousedownイベントを返します。 mousedownを停止するとクリックが誘発されないようにするかどうかは分かりません。 – JasperZelf

関連する問題