0

Im trying to build an app with Cytoscape.js and Angular2+. The Core part take place in a single service (cy.service). I add all Eventlisteners in a single function and call it after the cy init.

eg:

initEventlisteners(){
  cy.on('tap', this.handler);
  cy.on(...);
  ...
}

handler(event: any){
 console.log('something');
}

If I wrap console.log in a helper-function like that:

helper(){
 console.log('something');
)

And use it in the handler-function

handler(event:any){
 this.helper();
}

It calls: helper() is not a function. Thats a big problem that a cant use other functions inside the handler. Any ideas how to solve that problem ?

frm
  • 35
  • 4

1 Answers1

0

That's because with binding like this cy.on('tap', this.handler); you are loosing scope of variable. You should use it in this way cy.on('tap', (event) => { this.handler(event) }); (if it's passing any event object) or cy.on('tap', this.handler.bind(this));.

The frist approach with () => { } is called arrow function, which preserve current scope of variables. It's a new feature of ES6 specification. However you don't have to be afraid, angular compiler will convert it to backward compatible to ES5.

The second approach .bind(this) just simply binding this method to current scope where it's was called.

Patryk Brejdak
  • 1,571
  • 14
  • 26
  • One additional question: How can I explain that its possible to use normal variables in this-scope without .bind(this) ? – frm Dec 09 '17 at 00:11
  • It's a bit more complicated,look at this [answer](https://stackoverflow.com/a/45762505/4700863) and answers below, maybe you will find answers. – Patryk Brejdak Dec 09 '17 at 09:19