1
  constructor() {

    document.addEventListener('someEvent', function(event) {
      console.log(event.data);
      this.test(); //throws error - this.test() is undefined
    });
  }

If I move it to ngOnInit, it works fine:

  ngOnInit() {
    this.test(); //works ok
  }

The function is just a method on the component, defined after the constructor:

  public test(){
    console.log('TEST');
  }

My end goal is to run the test() method of my component every time someEvent event fires on the global window (the event comes from raw javascript, i.e. document.dispatchEvent(event, {'detail': evntPayload});

How do I accomplish this?

VSO
  • 11,546
  • 25
  • 99
  • 187
  • 1
    "this" always holds the reference to its surrounding function therefore you are referencing the anonymous function. One way to handle that is before adding the eventlistener add the line "var that = this;". Now you can call that.test(); Or use the arrow operator as stated in the answers. – sascha10000 Mar 22 '17 at 21:07
  • Hey Sascha - the `var self = this` is generally a good javascript solution for a number of things, but I was really looking for Gunter's answer here, since it's Angular 2 specific. – VSO Mar 23 '17 at 12:44
  • Yes true, I should've seen it by the ngOnInit(). The "lambda" way is the better solution. – sascha10000 Mar 23 '17 at 19:06

2 Answers2

2

Use arrow functions to keep this pointing to the current class instance

  constructor() {

    document.addEventListener('someEvent', (event) => { // <<< changed
      console.log(event.data);
      this.test(); //throws error - this.test() is undefined
    });
  }
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
1

Following link should solve what you need. Just bind to different event.

Angular window resize event

Community
  • 1
  • 1
Jan Cejka
  • 321
  • 1
  • 4