0

I have:

 connect(id: string) {
    console.log(id);
    this.connection = this.api.connect(id);
    this.connection.on('open', function () {
      this.testConnect();
    });
  }

testConnect(){

  }

I want to be able to call the testConnect function from within the this.connection.on

Pete
  • 2,325
  • 3
  • 16
  • 22

2 Answers2

1

do the following

let _that = this;
this.connection.on('open', function () {
  _that.testConnect();
});

Why I did this? because this in javascript is tied to a function so the callback function has it's own this that is totally different from the class one!, note that class in typescript is compiled into an function... try the TypeScript Playground to understand what I'm saying

Khaled Al-Ansari
  • 3,910
  • 2
  • 24
  • 27
0

Use an arrow function:

this.connection.on('open', () => {
  this.testConnect();
});
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177