0

I have a single callback that I'd like triggered by multiple events. I tried

userIsActive(){
  //do something
}
@HostListener('document:mousemove') this.userIsActive;
@HostListener('document:keypress') this.userIsActive;
@...

But it doesn't work, duplicate identifier 'userIsActive'. I know I can define new functions as callbacks,

@HostListener('document:mousemove') foo1(){ userIsActive(); };
@HostListener('document:keypress') foo2(){ userIsActive(); };
@...

but creating 2 new functions with arbitrary numbers seems unnecessary and less readable. Is there a way to pass a reference to an existing callback to @HostListener?

adamdport
  • 11,687
  • 14
  • 69
  • 91

1 Answers1

3

There is no need to define multiple methods, you can just decorate the same method multiple times.

For example:

  @HostListener('window:keyup')
  @HostListener('window:keydown')
  handle() {
    console.log('happened')
  }
toskv
  • 30,680
  • 7
  • 72
  • 74
  • It technically doesn't answer the question but it's good enough for my purposes. For whoever ends up here in the future, is there a way to reference an existing function or no? – adamdport Jun 07 '17 at 21:17
  • that is how you reference it multiple times you write it once and decorate it multiple times, or do you mean a function you don't write yourself? Something from another class or library maybe? – toskv Jun 08 '17 at 07:08
  • Yes, referencing a function from any import, can it be done? – adamdport Jun 08 '17 at 13:08
  • maybe using the renderer directly check out https://stackoverflow.com/questions/35080387/dynamically-add-event-listener-in-angular-2 – toskv Jun 08 '17 at 13:20