如何制作长按键时触发的KeyboardEvent流? (镖)

时间:2016-01-11 06:21:57

标签: stream dart angular

如何在长按一些html元素中的键时创建一个KeyBoardEvent流。

同样,我也对Angular2指令(longpress)感兴趣(具有相同的想法)。

1 个答案:

答案 0 :(得分:1)

@Directive(
    selector: '[longpress]')
class LongPress {
  @Output() EventEmitter<KeyboardEvent> longpress =
      new EventEmitter<KeyboardEvent>();

  KeyboardEvent _startEvent;
  @Input() Duration longpressDelay = new Duration(seconds: 2);
  Timer timer;

  @HostListener("keydown", const [r"$event"])
  @HostListener("keyup", const [r"$event"])
  void keyEventHandler(KeyboardEvent event) {
    if (_startEvent == null ||
        _startEvent.type != event.type ||
        _startEvent.keyCode != event.keyCode) {
      if (timer != null) {
        timer.cancel();
      }
      _startEvent = event;

      if(event.type == 'keyup') {
        timer = new Timer(longpressDelay, () {
          longpress.add(_startEvent);
          timer = null;
        });
      }
    }
  }
}

并像

一样使用它
<label for="input">Longpress: </label><input id="longpress" longpress (longpress)="longPressed($event)">

我还没弄明白让指令选择器与(...)一起工作,所以这也有效:

<label for="input">Longpress: </label><input id="longpress" (longpress)="longPressed($event)">

事件处理(preventDefault)似乎无法正常运行。 将此指令添加到<input>会中断写入输入。

解决方法是以这种方式订阅keydown / keyup

LongPress(ElementRef elementRef) {
  (elementRef.nativeElement as Element).onKeyDown.listen(keyEventHandler);
  (elementRef.nativeElement as Element).onKeyUp.listen(keyEventHandler);
}